next js api route relative path
Answered
Banjara Hound posted this in #help-forum
Banjara HoundOP
when i have a route like this "http://localhost:3000/api/random"
why i can't call it like this.
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:300013 Replies
like in server function
Banjara HoundOP
in middleware.
@Banjara Hound in middleware.
1 option is to set a env .env, like
API_URL=http://localhost:3000Answer
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 https://stackoverflow.com/questions/76995053/how-to-use-relative-path-fetch-in-nextjs-app-router
Alright, can you mark my answer as a solution.
@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.