Next.js Discord

Discord Forum

Calling internal api route from middleware

Answered
Short mackerel posted this in #help-forum
Open in Discord
Short mackerelOP
Hi Everyone, I'm looking to call internal API routes from the middleware using relative paths. However, since Next.js middleware no longer supports relative paths starting from version 12.1, is there an alternative approach to achieve this? I've tried using http://localhost:8080, http://0.0.0.0:8080, and http://127.0.0.1:8080, but none of them are working.
Answered by B33fb0n3
If you want to call your own endpoint, you can't avoid it. Even with rewrite it's not possible. But what you can do is to call the code inside your middleware. Then it will never leave the server.

Btw: when the middleware makes a request to your server endpoint, the whole request can only be read by your middleware

--- Edit
It might have to do with this: https://nextjs-forum.com/post/1336705281350041731#message-1337035384055529493
View full answer

13 Replies

Roseate Spoonbill
@Short mackerel I'd probably look into NextResponse.rewrite with URL created with base to the url that came with the request.

For example new URL('../../asd', 'https://google.com/some/result/page') produces https://google.com/asd, so you can combine it with the middleware rewrites. Now that I look into the docs, I see that Next even has some examples that do relative rewrites: https://nextjs.org/docs/app/building-your-application/routing/middleware#conditional-statements
@Short mackerel Thank you, but it will send the request out of the server, I want to avoid that.
If you want to call your own endpoint, you can't avoid it. Even with rewrite it's not possible. But what you can do is to call the code inside your middleware. Then it will never leave the server.

Btw: when the middleware makes a request to your server endpoint, the whole request can only be read by your middleware

--- Edit
It might have to do with this: https://nextjs-forum.com/post/1336705281350041731#message-1337035384055529493
Answer
Short mackerelOP
I want to call the api from middleware and consume it with in middleware
@B33fb0n3 do this: https://discord.com/channels/752553802359505017/1336705281350041731/1336737521027121163 <--- click
Short mackerelOP
Can you please help me in understanding why localhost or 0.0.0.0 or 127.0.0.1 are not working in middleware api call.
@Short mackerel Can you please help me in understanding why localhost or 0.0.0.0 or 127.0.0.1 are not working in middleware api call.
I think it's because that these network configurations can be different in different environments and different network configurations. The middleware is just a middleware. A file that will be executed before your pages
@Short mackerel solved?
@B33fb0n3 <@1336700461037916170> solved?
Short mackerelOP
Thank you it's working
happy to help