
⚫ getServerSideProps
- getServerSideProps라는 function을 export하면 Server Side Rendering이 된다.
이 function에 어떤 코드를 쓰든, 그 코드는 server에서 돌아가게 된다. (client 쪽이 아니라 server 쪽에서만 작동한다. 이걸 이용해서 API key를 숨길 수도 있다.)
[index.js]
import Seo from "../components/Seo";
export default function Home({ results }) {
return (
<div className="container">
<Seo title="Home" />
{results?.map((movie) => (
<div className="movie" key={movie.id}>
<img
alt={movie.title}
src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
/>
<h4>{movie.title}</h4>
</div>
))}
<style jsx>{`
.container {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 20px;
gap: 20px;
}
.movie {
cursor: pointer;
}
.movie img {
max-width: 100%;
border-radius: 12px;
transition: transform 0.2s ease-in-out;
box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;
}
.movie:hover img {
transform: scale(1.05) translateY(-10px);
}
.movie h4 {
font-size: 18px;
text-align: center;
}
`}</style>
</div>
);
}
export async function getServerSideProps() {
const { results } = await (
await fetch(`http://localhost:3000/api/movies`)
).json();
return {
props: {
results,
},
};
}
이 function 안에서 object 하나를 return하는데, props라는 key를 가지고 값으로는 fetching한 데이터를 object에 가지는 속성을 넣어주면 된다.
- 이 result는 Home의 args로서 받아올 수 있다.
route에 해당하는 component가 _app.js의 Component로 들어가고, getServerSideProps의 results가 _app.js의 pageProps로 들어가 해당 component의 prop으로 들어가게 된다.
- 검색엔진은 서버 사이드 렌더링을 좋아한다. 소스코드에 이미 많은 정보가 들어 있기에
'♠️ Next.js 12' 카테고리의 다른 글
| Next.js 12 - 시작하기 (2) | 2025.05.26 |
|---|---|
| Next.js 12 - Dynamic Routes (0) | 2025.03.11 |
| Next.js 12 - public dir, API key 숨기기(redirects, rewrites) (0) | 2025.03.10 |
| Next.js 12 - Layout, Head component (0) | 2025.03.10 |
| Next.js 12 - Global Style (0) | 2025.03.07 |