Next.js:在中间件中使用app目录处理时显示未找到页面。

huangapple go评论117阅读模式
英文:

Nextjs: show not-found page when handle in middleware using app dir

问题

我有一个使用nextjsapp目录。

该应用程序支持多语言:/[lang]/<router>

[lang]对于所有路由都是必需的,并且只包含某些语言。

我想验证[lang]是否正确。如果不正确,显示not-found.tsx

app支持not-found.tsx,所以我不想创建一个404/page.txs_404/page.tsx或类似的内容。

我想在middleware.ts中处理。

例如,我支持两种语言:envi。路由应该是/en/<route>/vi/<route>

如果用户访问类似于/abc/xyz/foobar的内容,应该显示not-found.tsx

我该如何做到这一点?

英文:

I have a nextjs using app dir.

The app suport multi language: /[lang]/&lt;router&gt;.

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/&lt;route&gt; or /vi/&lt;route&gt;.

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

How can I do that?

答案1

得分: 1

如果您正在使用App目录,您可以在您的[lang]文件夹内的layout.tsx中非常轻松地处理这个问题。只需像这样做:

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 (
        <>
            {/* 您的布局外观 */}
            {children}
        </>
    );
}

有关更多信息,请查看此处的文档:https://nextjs.org/docs/app/building-your-application/routing/internationalization

英文:

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 &#39;next/navigation&#39;;


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

}

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

huangapple
  • 本文由 发表于 2023年7月6日 13:47:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定