Willem Beké
Willem Beké

Reputation: 31

How to set the public path of my images with the locale in nextjs 13?

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

Answers (1)

Joel Davey
Joel Davey

Reputation: 2623

You have two options, depending on your needs

  1. You only have one source of assets so in /public/images (your folder directory) your going to link to these from all locales

Then you need to simply skip redirection for these assets, something like below adding to the matchers section

 "/((?!images).*)",
  1. Alternatively you might have have localised structure within there /public/images/en/ in which case Adrian Lee's solution might be appropriate by modifying the path with a find an replace.

Upvotes: 2

Related Questions