QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.28k stars 59 forks source link

defaultLocale is not working and always uses en #272

Closed rezaaa closed 11 months ago

rezaaa commented 11 months ago

This is my middleware, and my defaultLocale is "fa" but it doesn't work and uses the en as the default when I delete en or change the en to another language like fr, the default locale works!


import { NextRequest } from "next/server"
import { withAuth } from "next-auth/middleware"
import { createI18nMiddleware } from "next-international/middleware"

const locales = ["fa", "en"]
const publicPages = ["/", "/auth"]

const I18nMiddleware = createI18nMiddleware({
  locales,
  defaultLocale: "fa",
})

const authMiddleware = withAuth((req) => I18nMiddleware(req), {
  callbacks: {
    authorized: ({ token }) => token != null,
  },
  pages: {
    signIn: "/auth",
  },
})

export default function middleware(req: NextRequest) {
  const publicPathnameRegex = RegExp(
    `^(/(${locales.join("|")}))?(${publicPages.join("|")})?/?$`,
    "i"
  )
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname)

  if (isPublicPage) {
    return I18nMiddleware(req)
  } else {
    return (authMiddleware as any)(req)
  }
}

export const config = {
  matcher: ["/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)"],
}
QuiiBz commented 11 months ago

That's related to how the locale is resolved by default: we're extracting the Accept-Language header and trying to find a locale (within the locales option) that matches. If one is found, this locale is used, and defaultLocale isn't - the latter is only used when we cannot find any matching locale with the Accept-Language header.

You can override this logic using the resolveLocaleFromRequest option: https://next-international.vercel.app/docs/app-middleware-configuration#override-the-users-locale-resolution

In your case, you'll likely want to return "fa", if you always want your users to use this locale by default, instead of using their preferred one if available.