awolfe76
awolfe76

Reputation: 245

Next.js getServerSideProps use /api locally, in PR preview, and in production

This is almost directly from some of the example on the Next.js site.

function HomePage(props) {
  return (
    <div>
      <p>Welcome to {props.data.name} Next.js!</p>
      <img src="/conexon-logo-white.png" alt="my image" />
    </div>
  );
}

// This gets called on every request
export async function getServerSideProps(context) {
  const res = await fetch('http://localhost:3000/api/test');
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}

export default HomePage;

That code works great locally of course. But how can I replace the http://localhost:3000 with something "dynamic" depending on where the site is running? The site could be running locally (localhost), a preview URL created by Vercel (something-random.now.sh), another Vercel URL (something-else.now.sh), or a custom URL (mydomain.com). Is there a way to determine how to make that call the Next.js /api on all of those without a .env file? With the .env file I wouldn't know how to set it for the "dynamic" URLs created by Vercel for previews (and other Vercel URLs).

Thanks!

Upvotes: 2

Views: 4792

Answers (1)

hangindev.com
hangindev.com

Reputation: 4873

You can get the URL of the deployment by setting the System Environment Variable VERCEL_URL populated by Vercel.

  1. Visit your project setting page in Vercel.
  2. In the "Environment Variables" section, enter VERCEL_URL as Name, leave the Value empty, and click Add.
  3. Repeat for the Preview environment.

You can learn more about System Environment Variables in this Vercel Docs.

Then, inside getServerSideProps, you can get the URL with process.env.VERCEL_URL.

Please note that with this method, you can get the preview URL(something-random.now.sh) and production URL(something-else.now.sh) under different environments. But when you visit your custom domain(exmaple.com), you will still get the production URL.

This solution may be good enough if you are only using your custom URL but not Vercel's production URL:

let baseUrl = 'http://localhost:3000'
if(process.env.Vercel_URL) {
  baseUrl = process.env.Vercel_URL === 'https://something-else.now.sh'? 'https://exmaple.com': process.env.Vercel_URL
}

If you need both custom URL and Vercel's production URL to work, you may need another solution.

Upvotes: 4

Related Questions