Next.js
[Next] getServerSideProps 사용 시 url에서 query 정보 가져오기
Chunho
2022. 8. 5. 17:55
NextJS에서 SSR을 하는 중, 서버사이드에서 데이터를 받아올 때 url에 있는 id값을 사용해 서버에 요청을 해야했다.
이 때 getServerSideProps가 제공하는 context 파라미터를 사용하여 query 정보를 가져올 수 있었다.
context 파라미터에는 query 데이터를 제외하고도 여러가지 정보가 포함되어 있다.
url에 있는 query를 가져오기 위해서는 context.query를 사용하면 된다.
export async function getServerSideProps(context: GetServerSidePropsContext) {
const cookie = getServerSidePropsUserCookie(context)
const props: IProps = {
data: undefined
}
const {id} = context.query
setAxiosCookie(cookie)
try {
props.data = await getOrderById(Number(id))
} catch (e: any) {
handleServerSideApiError(e.status)
}
return {props}
}
위와 같이 context.query에서 id 값을 받아온 뒤, 해당 id를 사용하여 서버사이드에서 API에 요청을 할 수 있었다.