Next.js middleware get available locales

Viewed 182

i created i18n.json

i18n.json

{
  "locales": ["en-US", "tr-TR"],
  "defaultLocale": "tr-TR",
  "defaultNS": "common",
  "pages": {
    "*": ["common"]
  }
}

i want to get locales ["en-US", "tr-TR"] values in _middleware.tsx

i created _middleware.tsx and I have read the directions in this document https://nextjs.org/docs/api-reference/next/server#nextrequest nextUrl includes i18n so i want to reach locales in i18n object but I get undefined value.

 import { NextResponse, NextRequest } from "next/server";
    
 export async function middleware(req: NextRequest) {

   const { i18n } = req.nextUrl;
   const { locales } = i18n;

   console.log(locales);

   return NextResponse.next();
 }

How can I get the available locales values?

2 Answers

I'm not quite sure why you need middleware for this case, you can get all locales from the SSR props, but you need to configure

First, you need to define your locales in next-18next.config.js

module.exports = {
  i18n: {
    defaultLocale: "de",
    locales: ["de", "en"],
  },
};

Then in next page get all locales with SSR Props

export const getServerSideProps: GetServerSideProps = async ({ locales }) => {
   console.log(locales) // You should get an array of all locales
}

For now, best way to do this is importing next-i18next.config.js manually.

next-i18next.config.js

module.exports = {
  i18n: {
    defaultLocale: "en",
    locales: ["en", "tr"],
    localeDetection: false,
  },
};

middleware.js

import { i18n } from "./next-i18next.config.js";

export function middleware(req) {
   const availableLocales = i18n.locales;
}

You can import your i18n.json to achieve same.

Related