Next.js Discord

Discord Forum

Middleware config matcher issue

Unanswered
jy posted this in #help-forum
Open in Discord
jyOP
Following the documentation for NextJS Internationalization, i made this middleware.ts in the root directory (using App Router btw)
import { NextRequest, NextResponse } from "next/server";
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'

export type Locales = 'en' | 'zh'
export const locales: Locales[] = ['en', 'zh']
export const localeLabels: Record<Locales, string> = {
    'en': 'English',
    'zh': '中文',
}
const defaultLocale: Locales = 'en'


// Get the preferred locale, similar to the above or using a library
function getLocale(request: NextRequest) {
    const headers = { 'accept-language': request.headers.get('accept-language') ?? '' }
    const languages = new Negotiator({ headers }).languages()
    return match(languages, locales, defaultLocale)
}

export function middleware(request: NextRequest) {
    const { pathname } = request.nextUrl
    const pathnameHasLocale = locales.some(
        (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
    )

    if (pathnameHasLocale) return

    const locale = getLocale(request)
    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
        // '/'
    ],
}

1 Reply

jyOP
but when i ran npm run dev, im getting the error below
./middleware.ts:33:23
Invalid page configuration
  31 | }
  32 |
> 33 | export const config = {
     |                       ^
> 34 |     matcher: [
     | ^^^^^^^^^^^^^^
> 35 |         // Skip all internal paths (_next)
     | ^^^^^^^^^^^^^^
> 36 |         '/((?!_next).*)',
     | ^^^^^^^^^^^^^^
> 37 |         // Optional: only run on root (/) URL
     | ^^^^^^^^^^^^^^
> 38 |         // '/'
     | ^^^^^^^^^^^^^^
> 39 |     ],
     | ^^^^^^^^^^^^^^
> 40 | }
     | ^^
  41 |

Page config in middleware.ts is deprecated. Replace `export const config=…` with the following:
Visit https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config for more information.

and i tried setting the matcher to empty and it also returns this error, what is wrong?