Search code examples
next.jslocalizationvercel

Next.JS: How to use localized API routes when running on localhost, or alternatively how to have a single API route for all locales


I'm seeing an issue with my localized Next.js app's API Routes. When I am on a localized version of my site that is running on the localhost, the API routes to my server functions include the locale, which results in 404 errors.

I fetch the route in the client like this:

const res = await fetch(`api/route/path`);

This works when I am on my default locale (en), but if I have a different locale in the url, the fetch fails with a 404:

GET http://localhost:3000/ko/api/route/path 404 (Not Found)

When I deploy my site to Vercel, this issue does not happen. From what I can tell, that's because it deploys serverless functions for every locale I specify in my next.config.js.

My next.config.js

const nextConfig = {
  i18n: {
    locales: [
      'en',
      'de',
      'ko',
    ],
    defaultLocale: 'en',
  },
  // ...
};

module.exports = nextConfig;

TL;DR

How can I get localized API routes working in my Next.JS app when running on a localhost? I do not intend on having different behavior on my API for different locales, so is there a way to route all API calls through a single API rather than having serverless functions for each locale?


Solution

  • I found out what the issue was. The API route path in the fetch did not have a forward slash at the start, which was resulting in them not being appended as absolute paths on my domain.

    So, the path in the fetch should be /api/route/path, and not api/route/path.

    Without the forward slash, the path name was appended relative to the URL, which would include the locale when running on the localhost.