Next.js Discord

Discord Forum

Editing middleware to contain language in url between pages?

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
let locales = ["en", "es"];

// Get the preferred locale, similar to the above or using a library
function getLocale(request) {
  return "en";
}

export function middleware(request) {
  // Check if there is any supported locale in the pathname
  const { pathname } = request.nextUrl;
  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) return;

  // Redirect if there is no locale
  const locale = getLocale(request);
  request.nextUrl.pathname = `/${locale}${pathname}`;
  // e.g. incoming request is /products
  // The new URL is now /en-US/products
  return Response.redirect(request.nextUrl);
}

export const config = {
  matcher: [
    // Enable a redirect to a matching locale at the root
    "/",

    // Set a cookie to remember the previous locale for
    // all requests that have a locale prefix
    "/(es|en|br)/:path*",

    // Enable redirects that add missing locales
    // (e.g. `/pathnames` -> `/en/pathnames`)
    "/((?!_next|_vercel|.*\\..*).*)",
  ],
};

This is my current middleware file

what do I need to change in order to keep the value between pages for approved lanagues?

0 Replies