#When I'm using fetch in a server component, how do I get the right absolute URL?

1 messages · Page 1 of 1 (latest)

sage coral
#

Server components require an absolute URL in fetch—how do I determine that URL using environment variables?

modest shuttleBOT
#

Hi @sage coral. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can determine the absolute URL for server components in Next.js using environment variables. The process.env object can be used to access environment variables in your application.

For instance, if you're using Vercel for deployment, you can use the VERCEL_URL environment variable to get the base URL of your application. If VERCEL_URL is detected, the default value for metadataBase is <https://${process.env.VERCEL_URL}.> If it's not detected, it falls back to <http://localhost:${process.env.PORT> || 3000}.

Here's an example of how you might use this in a fetch request:

import fetch from 'node-fetch';

export default async function handler(request, response) {
 const res = await fetch(`<https://${process.env.VERCEL_URL}/api-endpoint`,> {
 method: 'POST',
 body: JSON.stringify({
 client_id: process.env.CLIENT_ID,
 client_secret: process.env.CLIENT_SECRET,
 }),
 headers: { 'Content-Type': 'application/json' },
 });

 const data = await res.json();
 return response.status(200).json({ data });
}

In this example, VERCEL_URL is used to construct the URL for the fetch request. CLIENT_ID and CLIENT_SECRET are also accessed from process.env and used in the request body.

Remember to add these environment variables to your Vercel project settings. The values are encrypted at rest and permission to view values can be restricted based on your role. You can also choose a specific Git branch to set Environment Variables for with the Preview environment.

When overriding the default, it's recommended to use environment variables to compute the URL. This allows configuring a URL for local development, staging, and production environments.