Next.js Discord

Discord Forum

Type error for: process.env.VERCEL_URL

Answered
Ladder-backed Woodpecker posted this in #help-forum
Open in Discord
Avatar
Ladder-backed WoodpeckerOP
I am getting this error message on one of my routes:
TypeError: Invalid base URL string.
    at (middleware.js:16:6)
    at (node_modules/next/dist/esm/server/web/adapter.js:152:19)


It is saying that the base URL in my middleware is invalid:

 if (session == null && req.nextUrl.pathname !== "/") {
    return NextResponse.redirect(
      new URL("/", process.env.VERCEL_URL || "http://localhost:3000")
    );
  }


Is the VERCEL_URL environment variable something I need to set up myself in the Vercel project settings similar to database keys? I thought this was automatically done?

Appreciate any help in fixing this one.
Answered by fuma & joulev pray for Schneider
VERCEL_URL doesn’t contain the protocol schema, it should be https://${process.env.VERCEL_URL} instead.

Btw, in middleware. we usually use new URL(“/“, req.url) instead of getting the absolute path
View full answer

8 Replies

Avatar
Ladder-backed WoodpeckerOP
This is what I am getting
Image
Avatar
fuma & joulev pray for Schneider
VERCEL_URL doesn’t contain the protocol schema, it should be https://${process.env.VERCEL_URL} instead.

Btw, in middleware. we usually use new URL(“/“, req.url) instead of getting the absolute path
Answer
Avatar
Ladder-backed WoodpeckerOP
Ah I see. Thanks for that. (I am a new dev).
In your middleware suggestion, would the req.url be the base URL? For example, if someone going to
www.example.com/authgatedstuff
needs to be redirected to
www.example.com/
. Would the req.url here be just
www.example.com
?
Avatar
fuma & joulev pray for Schneider
Yes, the second parameter of new URL is base url
Avatar
Ladder-backed WoodpeckerOP
I see thank you!
Btw, off topic, I was looking at your profile and saw that you are in HK. I am from HK too! (But don't live there now)
Avatar
fuma & joulev pray for Schneider
#off-topic