Next.js Discord

Discord Forum

How to get `origin` aka baseURL?

Unanswered
Turkish Angora posted this in #help-forum
Open in Discord
Turkish AngoraOP
Hello, I need the origin/baseURL for fetch/new URL.
I need it in server and client code.
What is the easiest setup to accomplish that in Next.js?

i.e.
// should be usable anywhere
const url = new URL('/api', process.env.ORIGIN)
// on `main` branch deployment `ORIGIN` would return `https://example.com`
// on `stagging` branch deployment `ORIGIN` would return `https://example.dev`
// on any other branch deployment `ORIGIN` would return process.env.VERCEL_URL
// on `npm run dev` would return dev url like `http://localhost:3000`

1 Reply

in client, you can just use relevive urs (ie /api), on server you shouldnt be fetching itself: https://nextjs-faq.com/fetch-api-in-getserversideprops