Next.js Discord

Discord Forum

next js api route relative path

Answered
Banjara Hound posted this in #help-forum
Open in Discord
Banjara HoundOP
when i have a route like this "http://localhost:3000/api/random"
why i can't call it like this.
await fetch("api/random")

or

await fetch("/api/random")

and have to call it with full url.

await fetch("http://localhost:3000/api/random")
Answered by Anay-208
1 option is to set a env .env, like
API_URL=http://localhost:3000
View full answer

13 Replies

Banjara HoundOP
in middleware.
@Banjara Hound in middleware.
1 option is to set a env .env, like
API_URL=http://localhost:3000
Answer
and use process.env.API_URL + "/path"
in fetch
Banjara HoundOP
with vanilla js that possible. why is not possible with next js?
I think the middleware doesn't have access to your url. the frontend does have using window.location
Banjara HoundOP
thanks. i found my answer. relative path only work when is client side. in server side have to be absolute url.
@Banjara Hound thanks. i found my answer. relative path only work when is client side. in server side have to be absolute url.
yes, if you fetch inside middleware, you could do this
export function middleware(req: NextRequest) {
  fetch(new URL("/api", req.url))
}
Banjara HoundOP
ok thanks.