admin管理员组文章数量:1357615
I am new on NextJs and for my projext I am using NextJs 15.
My project is a blog site that will be use for different domain. For example domain1, domain2, ...., all those site will be served by my single application.
To manage all domain I need to retreive the site conf from an external API.
My problem is how to share the configuration between all server components.
Until now I get the domain information from headers and then call the API to get the config.
Now I want to implement generateMetadata
function and I need the config info there.
In static route (/home
) I can read headers outside the Page() function, but for dynamic route (/articles/[id]
) headers are not available from there, so I don't know how to get the domain and the config.
Following and example:
const domain = await getDomain();
const config = await getBlogConfig(domain);
export async function generateMetadata() : Promise<Metadata> {
console.log('generateMetadata', await parent);
return generateSiteMetadata({
config,
title: 'Home',
keywords: ['parola chiave', 'altra parola chiave'],
image: '.jpg',
});
}
export default async function Page() {
return (...)
}
Then my functions to get domain and blogConfig:
export const getDomain = cache(async (): Promise<string> => {
const headersList = await headers();
domain = headersList.get('host') || '';
return domain;
});
export async function getBlogConfig(domain: string): Promise<BlogConfig> {
const response = await fetch(`${API_URL}/api/sites/${domain}`, {
headers: {
'Content-Type': 'application/json',
},
next: {
revalidate: CACHE_TTL.config,
},
});
if (!response.ok) {
throw new Error('Failed to fetch blog config');
}
const result: ApiResponse<BlogConfig> = await response.json();
return result.data;
}
This works fine for static route, but not for dynamic route:
Error:
headers
was called outside a request scope. Read more:
How can I solve this?
Thanks.
本文标签: reactjsNextjs share variable across all server componetStack Overflow
版权声明:本文标题:reactjs - Nextjs share variable across all server componet - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744078261a2587151.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论