最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Nextjs share variable across all server componet - Stack Overflow

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论