Next.js中的运行时环境变量generateMetadata

问题描述 投票:0回答:1

我正在使用 Next.js 并尝试在运行时设置环境变量来更改一些元数据。从 Next.js 文档中的 description 来看,我预计这会起作用。在构建时设置变量效果很好,但在运行时无法覆盖。

例如,这确实很有帮助,因此我只需要为登台和生产环境构建单个映像。

我使用

npx create-next-app

 创建了一个最小的可重现示例,并更改 
app/layout.tsx
 以使用环境变量作为标题:

import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; const inter = Inter({ subsets: ["latin"] }); export async function generateMetadata(): Promise<Metadata | undefined> { return { title: process.env.META_TITLE, description: "Generated by create next app", } } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> ); }
这是

.env

META_TITLE="My App"
现在构建并运行应用程序工作正常:

npm run build
但是我无法在运行时更改

META_TITLE

export META_TITLE="My App (Staging)" npm run start
    
next.js environment-variables
1个回答
0
投票
解决方案非常简单。只需在

noStore

 函数中使用 
generateMetadata
 即可。这是工作示例:

import type { Metadata } from "next"; import { unstable_noStore as noStore } from 'next/cache' import { Inter } from "next/font/google"; import "./globals.css"; const inter = Inter({ subsets: ["latin"] }); export async function generateMetadata(): Promise<Metadata | undefined> { noStore() return { title: process.env.META_TITLE, description: "Generated by create next app", } } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> ); }
    
© www.soinside.com 2019 - 2024. All rights reserved.