英文:
Nextjs: show not-found page when handle in middleware using app dir
问题
我有一个使用nextjs
的app
目录。
该应用程序支持多语言:/[lang]/<router>
。
[lang]
对于所有路由都是必需的,并且只包含某些语言。
我想验证[lang]
是否正确。如果不正确,显示not-found.tsx
。
app
支持not-found.tsx
,所以我不想创建一个404/page.txs
或_404/page.tsx
或类似的内容。
我想在middleware.ts
中处理。
例如,我支持两种语言:en
和vi
。路由应该是/en/<route>
或/vi/<route>
。
如果用户访问类似于/abc
或/xyz/foobar
的内容,应该显示not-found.tsx
。
我该如何做到这一点?
英文:
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?
答案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 '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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论