Next.js Discord

Discord Forum

Middleware

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
Hi guys, Im using custom middleware for translations with following middleware.ts file:
import { NextResponse, NextRequest } from "next/server"; import acceptLanguage from "accept-language"; import { fallbackLng, languages } from "./app/i18n/settings"; acceptLanguage.languages(languages); export const config = { // matcher: '/:lng*' matcher: [ "/((?!api|_next/static|_next/image|assets|font|images|favicon.ico|sw.js).*)", ], }; const cookieName = "i18next"; export function middleware(req: NextRequest) { console.log(req.url); if ( req.nextUrl.pathname.indexOf("icon") > -1 || req.nextUrl.pathname.indexOf("chrome") > -1 ) return NextResponse.next(); let lng: string | null = null; if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName)!.value); if (!lng) lng = acceptLanguage.get(req.headers.get("Accept-Language")); if (!lng) lng = fallbackLng; // Redirect if lng in path is not supported if ( !languages.some((loc) => req.nextUrl.pathname.startsWith(/${loc})) && !req.nextUrl.pathname.startsWith("/_next") ) { return NextResponse.redirect( new URL(/${lng}${req.nextUrl.pathname}, req.url) ); } if (req.headers.has("referer")) { const refererUrl = new URL(req.headers.get("referer")!); const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(/${l}) ); const response = NextResponse.next(); if (lngInReferer) response.cookies.set(cookieName, lngInReferer); return response; } return NextResponse.next(); }

It works perfectly on localhost, but after deploy to custom host with custom server (https://nextjs.org/docs/pages/building-your-application/configuring/custom-server) Next keeps redirecting me back to localhost, example: https://tk4czyk.com (u will be automatically redirected to localhost:3000/en). But if youu enter https://tk4czyk.com/en it works perfectly.
Can u take a look?

5 Replies

Barbary LionOP
bump
Barbary LionOP
bump, need help ASAP
bump with more data. just typing bump isnt going to change the fact that the original message wasnt enough for anyone to want to help.
Barbary LionOP
What else could I provide here?
Next v135.3.3, i18next v22.4.9
file structure in screenshot, i18n client .
Source code:
https://github.com/kacyee/tkaczyk
Barbary LionOP
up