Reputation: 31
I'm creating a multilang website in Nextjs 13. Therefore I'm using the following middleware.ts file:
import { NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
export let locales = ["nl", "fr", "en", "de"];
export let defaultLocale = "nl";
function getLocale(request: NextRequest) {
let headers = { "accept-language": "nl,nl;q=0.5" };
let languages = new Negotiator({ headers }).languages();
return match(languages, locales, 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}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
// e.g. incoming request is /products
// The new URL is now /en-US/products
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
],
};
However, my images won't show on my website since the public path is set to /nl/images/some-image.jpg.
When deleting the rule "/((?!_next).*" in the matcher config, but of course this prevents my website from building and launching.
Does anyone know how I can solve this issue?
I deleted and tried some rules in the config of the matcher in my Middleware.ts file, however it did not work, because I don't really understand how to implement the matcher rules correctly.
Upvotes: 3
Views: 1770
Reputation: 2623
You have two options, depending on your needs
Then you need to simply skip redirection for these assets, something like below adding to the matchers section
"/((?!images).*)",
Upvotes: 2