SSR์ Server Side Rendering ์ฝ์๋ก, ์น์ฌ์ดํธ๋ฅผ ์ ์ํ์ ๋ ์๋ฒ๋ก๋ถํฐ ํ์ํ ๋ชจ๋ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์์ HTMLํ์ผ์ ๋ง๋ค๊ณ ํด๋ผ์ด์ธํธํํ ์๋ตํด์ฃผ๋ ๋ฐฉ์์ด๋ค.
๋ณด์ฌ์ง HTML ๋ด์ฉ์ด ํ์ผ์ ๋ด๊ฒจ ์๊ธฐ ๋๋ฌธ์ ํจ์จ์ ์ธ SEO๊ฐ ๊ฐ๋ฅํ๋ค. ๋ํ ์ด๋ฏธ ๋ง๋ค์ด์ง HTMLํ์ผ์ ๋ฐ์์์ ์น์ฌ์ดํธ๋ฅผ ๋ฐ๋ก ๋ณผ ์ ์๊ธฐ ๋๋ฌธ์ ์ด๊ธฐ ๋ก๋ฉ ์๋ ์ญ์ ๋น ๋ฅด๋ค.
ํ์ง๋ง ์์ง ๋์ ์ผ๋ก ์ ์ดํ ์ ์๋ ์๋ฐ์คํฌ๋ฆฝํธ ํ์ผ์ ๋ฐ์์ค์ง ์์๊ธฐ ๋๋ฌธ์ ํด๋ฆญ์ ์ฒ๋ฆฌํ ์๋ ์๋ค. ์ต์ข ์ ์ผ๋ก ์๋ฐ์คํฌ๋ฆฝํธ ํ์ผ์ ๋ฐ์์์ผ ์ธํฐ๋ ์ ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ด๋ค.
๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง์ ์ฌ์ฉ์๊ฐ ์น์ฌ์ดํธ๋ฅผ ๋ณผ ์ ์๋ ์๊ฐ๊ณผ ์ธํฐ๋ ์ ํ ์ ์๋ ์๊ฐ ์ฌ์ด ๊ณต๋ฐฑ์ด ์กด์ฌํ๊ฒ ๋๋ค.
๋ํ ์ฌ์ฉ์๊ฐ ํด๋ฆญ์ ํ๊ฒ ๋๋ฉด ์ ์ฒด ์น์ฌ์ดํธ๋ฅผ ๋ค์ ์๋ฒ์์ ๋ฐ์์ค๋ ๊ฒ๊ณผ ๋์ผํ๊ธฐ ๋๋ฌธ์ ํ๋ฉด ๊น๋นก์ ์ด์๊ฐ ๋ฐ์ํ๊ณ , ํด๋ฆญ์ ํ ๋๋ง๋ค ๋ค์ ์๋ฒ์ ์์ฒญํด ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ค๊ธฐ ๋๋ฌธ์ ์๋ฒ ๋ถํ๊ฐ ๋ฐ์ํ ์ ์๋ค.
์ด์ฒ๋ผ ๊ฐ๊ฐ์ ์ฅ๋จ์ ์ ๊ฐ์ง CSR๊ณผ SSR์ ์ ์ฐํ๊ฒ ์์ด ๋ชฉ์ ์ ๋ง๊ฒ ์ฌ์ฉํ ํ์๊ฐ ์๋ค.
์ฌ์ค ๊ฐ์ธํ๋ก์ ํธ๋ฅผ ํตํด SSR์ ์ฅ์ ์ ํฌ๊ฒ ๊ฒฝํํ๊ธฐ๋ ์ฝ์ง ์๋ค ํ์ง๋ง ์ค์ ๋ก ์ ์ฉํ๊ณ ๋์ ํ๋ ๊ฒฝํ์ ์์ผ๋ก๋ ๊ฐ๋ฐ์๋ก ์ญ๋์ ํค์ฐ๋ ๋ฐ ํฐ ๊ธฐํ๋ผ ์๊ฐํ๋ค.
https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
Next.js๋ ๊ธฐ๋ณธ์ ์ผ๋ก SSG๋ฐฉ์์ด default ๊ฐ์ผ๋ก ์ ํด์ ธ ์๋ค. ์ด ๋ง์ ์ฆ SSR ๋ฐฉ์์ ์ฌ์ฉํ๋ ค๋ฉด ๋ฐ๋ก ์ง์ ์ ํด์ผํ๋ค๋ ๊ฒ์ด๋ค.
์ ์ฉ๋ฐฉ๋ฒ getServerSideProps
์ด์ ๊ฐ์ด ๊ณต์๋ฌธ์์ ๋์์๋ค.
export async function getServerSideProps() {
const products = await client.product.findMany({});
console.log(products);
return {
props: {
products: JSON.parse(JSON.stringify(products)),
},
};
}
console.log(products);๋ฅผ ํตํด ๋ฐ์ดํฐ ๊ฐ์ด ์ค๋ ๊ฒ์ ํ์ธํ์๋ค.
const Home: NextPage<{products: ProductWithCount[]}> =({ products }) => {
const user = useUser()
console.log(user);
const { data } = useSWR<ProductsResponse>("/api/products/Index")
console.log(data);
const fetcher = (url: string) => fetch(url).then((response) => response.json());
const { data:profile } = useSWR("/api/users/Me", fetcher);
const router = useRouter();
-----
์ด๋ ๊ฒ ์ปดํฌ๋ํธ ์ต์๋จ์ Props๋ก ๋ด๋ ค์ฃผ๋ฉด ๋ฐ์์จ ๋ฐ์ดํฐ๋ฅผ ๋ฟ๋ ค ์ค ์ ๊ฐ ์๋ค.
SWRConfig ์ปดํฌ๋ํธ๋ fallback ์ด๋ผ๋ property ๋ก ์บ์ ์ด๊ธฐ ๊ฐ์ ์ค์ ํ ์ ์๋ค. ๊ทธ๋ฌ๋ฉด ์ด Home ์ปดํฌ๋ํธ๊ฐ /api/products/ ํค๋ฅผ ์ด์ฉํด์ ์บ์๋ฅผ ๋ถ๋ฌ ์ค๊ฒ ๋๋ค.
*fallback์๋ key-value ๊ฐ์ฒด๋ฅผ ํตํด ์บ์์ ์ด๊ธฐ๊ฐ์ ์ค์ ํ ์ ์๋ค.
return (
< SWRConfig value={{ fallback }}>
< Article />
< /SWRConfig>
)
}
const Page:NextPage<{products:ProductWithCount[]}> = ({ products }) => {
return <SWRConfig value={{
fallback: {
"api/products/Index" : {
ok:true,
products
}
}
}}>
<Home/>
</SWRConfig>
}