fetch
라던지 서버에서 일어나는 data 관련 작업을 모두 수행한 후에, 즉 API 관련 동작이 모두 완료 되었을때 페이지를 렌더링하는 방식을 사용할 수 있습니다. getServerSideProps
의 내부코드는 모두 서버에서 렌더링됩니다.rewrites
와 같이 API key 를 숨기는 방법 중 하나입니다.getServerSideProps
의 내부코드는 오직 백엔드(서버)에서만 실행되기 때문입니다!rewrites
사용 : SSR + CSR 방식getServerSideProps
사용 : SSR 방식getServerSideProps
라는 function 을 export
하면 됩니다.getServerSideProps
이름은 변경하면 안됩니다.getServerSideProps
에서 반환하는 객체의 props
키값으로 반환되는 객체의 키, 키값 페어를 활용하여 export default
하는 페이지 렌더링 컴포넌트에 props 로 전달하여 사용합니다._app.js
에서 App 컴포넌트의 pageProps
인자의 존재이유 입니다.// /pages/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 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 img {
max-width: 100%;
border-radius: 12px;
transition: transform 0.2s ease-in-out;
}
.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(
"https://api.themoviedb.org/3/movie/popular?api_key=b9a221486250d0601edc38**********"
)
).json();
return {
props: {
results,
},
};
}
rewrites()
, .env
사용fetch
되는 동안 로딩 화면 or html 태그 먼저 보여줌getServerSideProps()
를 통해 구현하는 방식fetch
되는 동안 아무것도 보이지 않고, 데이터 fetch
가 완료된 후 페이지 보여줌노마드코더 NextJS 시작하기
NextJS 공식문서