0

I have a nextjs using app dir.

The app suport multi language: /[lang]/<router>.

The [lang] is reqiured for all route and only have some language.

I want to validate the [lang] is correct. If not, show not-found.tsx.

The app support not-found.tsx so I dont want to create an 404/page.txs or _404/page.tsx or some thing similer.

I want to handle in middleware.ts.

Ex: I support 2 language : en and vi. The route shold be /en/<route> or /vi/<route>.

If user access to some thing like /abc or /xyz/foobar, not-found.tsx sould be display.

How can I do that?

kan
  • 73
  • 6
  • Hey! Since it's your second post in 2 hours regarding this matter, I recommend you go through one of the guides on how to implement i18n support, for example https://locize.com/blog/next-13-app-dir-i18n/ Particularly regarding middleware - that's what this question is about. – Gasanov Jul 06 '23 at 05:57

1 Answers1

1

If you are using the App dir you can very easily handle this in the layout.tsx inside of your [lang] folder. Simply do something like this:

import { notFound } from 'next/navigation';


export default function Layout({
    children,
    params,
}: {
    children: ReactNode;
    params: { lang: string };
}): JSX.Element {
    const langValid = ['es', 'vi'].includes(params.lang);
    
    if (!langValid) {
      return notFound();
    }
    
    return <>
      // Whatever your layout looks like
      {children}
    </>;

}

For more info on this, checkout the docs here: https://nextjs.org/docs/app/building-your-application/routing/internationalization

Henry Jeff
  • 57
  • 8
  • thanks for ur ans. But I got this: `Application error: a server-side exception has occurred (see the server logs for more information). Digest: NEXT_NOT_FOUND` – kan Jul 06 '23 at 08:28
  • I checked terminal and no log. (The root layout is `use client`). my code:: `if (!language.some((item) => item.key === params.lang)) { console.log('not found') return notFound() }` – kan Jul 06 '23 at 08:30