1

I tried to get it with window.location.href, it says window is undefined, i searched the internet for handling this and getting the url from server side but no results on next js 13, Do you have an idea?

CatalinPCE
  • 21
  • 5

1 Answers1

-1

You can't use window.location.href on the server since there is no browser window in server-side rendering.

  1. If you are deploying your app on Vercel, you can use process.env.NEXT_PUBLIC_VERCEL_URL (you can find all Vercel environment variables here).

For local development you'd need to add this variable to your .env file:

NEXT_PUBLIC_VERCEL_URL=localhost
  1. If you are not using Vercel for deployment, you can define your own environment variable in .env file:
NEXT_PUBLIC_HOSTNAME=my-website.com
  1. If your website can be accessed through multiple domains and you need to know the exact host name that was used for that particular request, then you can read the host name from the request headers:

App router:

import { headers } from "next/headers";

// ...

const host = headers().get("host");

Pages router:

export const getServerSideProps = async ({ req }) => {
  const { host } = req.headers;
  // ...
};

But please note that in this case your page will be rendered dynamically for each incoming request.

Igor Danchenko
  • 1,980
  • 1
  • 3
  • 13