Skip to content
Next.Js프로젝트

How I Fixed a 500 Error Caused by Next.js SSR

1 min readProjectsMoved from my Tistory blogRead the Korean original

500 error on an API call
Figure 1. 500 error on an API call

First, the cause of the 500 error is simple.

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

With Next.js SSR, before the API is called through useSWR on the client side,

that is, before the screen is drawn in the browser, the backend is called ahead of time with the initial values ({latitude: null, longitude: null}) to render the screen. So the latitude and longitude params were sent as null, and that caused the problem.

That's because the useCoords function, which gets the latitude and longitude, declares its initial values as {latitude: null, longitude: 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;
}

The fix is to call the API only when both latitude && longitude exist, when the screen is drawn on the client, that is, in the browser.

  • #Next.js
  • #SSR
  • #Frontend Developer Sungjun Um

More in Projects