Next.js Discord

Discord Forum

Issue with Middleware Redirect for Internationalization purposes

Unanswered
Greater Scaup posted this in #help-forum
Open in Discord
Greater ScaupOP
Hello everyone,

I'm currently working on a Next.js project and I'm facing an issue with my middleware that is not redirecting requests as expected. I'm using the middleware for internationalization purposes. Here's the relevant code snippet:

import { NextResponse, NextRequest } from 'next/server';
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';

let locales = ['en', 'es'];
let defaultLocale = 'en';

function getLocale(request: NextRequest) {
  // Retrieving languages from request headers
  let headers = { 'accept-language': 'en-US,en;q=0.5' };
  let languages = new Negotiator({ headers }).languages();
  let defaultLocale = 'en';
  let locale = match(languages, locales, defaultLocale);
  console.log(locale);
  return locale || defaultLocale;
}

export function middleware(request: NextRequest) {
  // Check if there is any supported locale in the pathname
  const pathname = request.nextUrl.pathname;
  const pathnameIsMissingLocale = locales.every(
    (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
  );

  console.log(pathnameIsMissingLocale);
  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);

    // Redirect to the URL with the determined locale
    return NextResponse.redirect(
      new URL(`/${locale}/${pathname}`, request.url)
    );
  }
}

export const config = {
  matcher: [
    // Skip all internal paths (_next)
    '/((?!_next).*)',
    // Optional: only run on root (/) URL
    // '/'
  ],
};

I expect the middleware to redirect requests that don't include a supported locale in the pathname. However, the redirection doesn't seem to be happening, and I'm unable to identify the cause of the issue.

Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you in advance for your help!

3 Replies

@Greater Scaup your code seems to be coming from the official doc and it is almost identical, so it should work i think.
and i deployed the code to my Vercel, it seems work right.

here is an output from cURL command:

curl -I -v https://xxxx.vercel.app/abc


< HTTP/2 307 
HTTP/2 307 
< cache-control: public, max-age=0, must-revalidate
cache-control: public, max-age=0, must-revalidate
< content-type: text/plain
< location: /en/abc
location: /en/abc
< server: Vercel
server: Vercel
(snip)


as you see, it returns HTTP status code 307 with location /en/abc. it also works from a Chrome browser on my mac.

one thing i noticed is, if it runs locally on my mac, location has a redundant slash like '/en//abc'

how does an output from cURL look like in ur side? hope this helps.
another advice is you can make use of debugger. luckily debugger works with middleware.ts, so you can run it step by step to reveal how it goes.
@tafutada777 another advice is you can make use of debugger. luckily debugger works with middleware.ts, so you can run it step by step to reveal how it goes.
Greater ScaupOP
I have resolved the issue; the problem occurred because I placed the Middleware in the root directory instead of the src directory.