본문 바로가기
Next.Js프로젝트

Next.Js의 SSR 방식으로 인해서 생긴 500 Error 해결 법

1분프로젝트티스토리에서 옮긴 글

API 호출 500 Error
그림 1. API 호출 500 Error

먼저 500 Error가 발생한 원인은 간단합니다.

ts
const { data } = useSWR<PostsResponse>(
    latitude && longitude
      ? `/api/posts?latitude=${latitude}&longitude=${longitude}`
      : null
);

Next.Js의 SSR 방식은 클라이언트 단에서 useSWR을 통해서 API Call을 호출하기 전에

즉 브라우저에 화면을 그려주기 전에 미리 초기 값({latitude: null, logintude: null})으로 백엔드에 호출을 해서 화면을 그리는 방식이기 때문에 param의 latitude, logintude의 값이 null로 전달되어서 발생한 문제입니다.

위도와 경도를 구하는 useCoords 함수는 초기값으로 각각 {latitude: null, logintude: null}으로 선언되어 있기 때문입니다.

ts
import { useEffect, useState } from "react";

interface UseCoordsState {
  latitude: number | null;
  longitude: number | null;
}

export default function useCoords() {
  const [coords, setCoords] = useState<UseCoordsState>({
    latitude: null,
    longitude: null,
  });
  const onSuccess = ({
    coords: { latitude, longitude },
  }: GeolocationPosition) => {
    setCoords({ latitude, longitude });
  };

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(onSuccess);
  }, []);
  return coords;
}

해결 방안은 클라이언트 즉 브라우저에서 화면을 그릴 때 latitude && logitude 값이 둘 다 존재할 때 API를 호출하면 됩니다.

  • #next.js
  • #SSR
  • #프론트엔드 개발자 엄성준

프로젝트의 다른 글