킹의 개발일지

getServerSideProps or API Routes 본문

Next.js

getServerSideProps or API Routes

k1ng 2023. 4. 27. 22:13

토이 프로젝트에서 데이터를 요청할 때는 getServerSideProps안에서 api routes를 사용했다. 아래 두 코드는 index.js를 렌더링 할 때 요청 되는 메서드들이다. 우선, '/' 가 요청되면 server side에서 api routes를 호출하고 api routes는 다시 날씨 api를 요청하여 결과를 리턴하는 구조이다.

 

export async function getServerSideProps(context) {
	const session = await getServerSession(context.req, context.res, authOptions)
	const url = process.env.WEATHER_REQ_URL +"/api/weather";
	const options = {
		method: "POST",
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ email: session.user.email })
	}
	const response = await fetch(url, options);
	const { data } = await response.json();
	return {
		props: {
			weatherData: data,
		}
	}

}

 

/page/api/weather

export default async function handler(req, res) {
	// '/api/weather' 호출 시 작동하는 핸들러   
}

 

뭔가 이상하게 홈 페이지로 이동할 때마다 이상하게 늦는(?) 감이 있었다.

 

성능 개선을 위해 이래저래 검색하다가 next.js 레퍼런스의 data fetching 섹션에서 다음을 발견했다.

 

결론을 말하면 내가 짰던 로직이 추가적인 요청을 보낸는 꼴이었고 성능 저하를 일으킨다는 것이었다. 그래서 getServerSideProps안에서 요청을 보내도록 코드를 개선한후, index 페이지로 가는데 얼마나 걸리나 체크해보고자 했다.


우선 내가 짰던 로직은 index.js로 라우팅 되고, 데이터 패칭후 렌더링 되는데, 3초가량이 걸린다.

(물론 build를 하지 않은 결과이다.)

 

코드를 다음과 같이, api routes 과정을 하나 생략하고 getServerSideProps에서 바로 날씨 api 요청을 보내서 시간을 단축시킬 수 있었다.

export async function getServerSideProps(context) {
	const session = await getServerSession(context.req, context.res, authOptions);
	const baseDate = getBaseDate();
	const encodedQureyUrl = weatherUrl + '?' + getRequestURL(session.address.x, session.address.y, baseDate);

	const response = await fetch(encodedQureyUrl, {
		method: "GET",
		headers: {
			'Content-Type': 'application/json',
			'Accept': 'application/json'
		},
	})

	if (response.ok) {
		const data = await response.json();
		const result = data.response.body.items;
		return {
			props: {
				weatherData: result,
			}
		}
	} else {
		const { error } = await response.json();
		return {
			props: {
				error: error,
			}
		}
	}

}

 

 



확실히 체감상 뚝뚝 끊김이 느껴지던것이 확연히 줄어듬을 체감할 수 있었다.

 

무슨 생각으로 두 단계에 나눠서 데이터를 요청 했는지는 모르겠지만.. 오늘의 결론... 레퍼런스를 잘 확인하면서 코딩 하자!!

 

결론! getServerSideProp 이든 api route든 어차피 서버에서 동작한다! 때문에 두 단계로 나눌 필요가 없었다!