How to get absolute URL in production?

Viewed 11218

The problem I'm facing is that I'm unable to get the absolute URL in the production build when using getStaticPaths and getStaticProps

export async function getStaticPaths() {
  const url =
    process.env.NODE_ENV === "development"
      ? "http://localhost:3000"
      : "https://websitename.vercel.app";
  const res = await fetch(`${url}/api/posts`);
  const posts = await res.json();
  console.log("posts: ", posts);

  const paths = posts.map(({ slug }) => ({
    params: { slug },
  }));

  console.log("Paths: ", paths);

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  console.log("params: ", params);
  const url =
    process.env.NODE_ENV === "development"
      ? "http://localhost:3000"
      : "https://websitename.vercel.app";
  const res = await fetch(`${url}/api/post`, {
    method: "POST",
    body: params.slug,
  });
  const post = await res.json();

  return {
    props: { post },
  };
}

It works fine in the development build but when it comes to production it fails because the hardcoded https://websitename.vercel.app is not the one generated by vercel. The URL generated by vercel is something like this websitename-q1hdjf6c2.vercel.app.

How do I fix this?

2 Answers

Unfortunately, since static site building process is done without an actual site running, the full URL is not accessible there. You can only access the full URL on the client side in the global window object.

You can also set an environment variable after Vercel generates a URL for your application and use it from there.

Related