N
Nuxt8mo ago
konsav

middleware/redirect.global.js

My project is in Nuxt3. I create a middleware in order to redirect when a user go to a specific route. And the redirect url is from an APi call. My problem is that API call become twice and i have this error on terminal [unhandledRejection] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
9 Replies
JuanP Barba
JuanP Barba8mo ago
Can you share an example? The API call is to an external server or is a Nuxt API endpoint?
konsav
konsavOP8mo ago
export default defineNuxtRouteMiddleware(async (to, from) => { const { $getApiData } = useNuxtApp(); if (to.path.includes("/test/") || to.path.includes("/test/abc")) { const data = await $getApiData.fetchData( $../redirect/url/${encodeURIComponent( to.fullPath )} ); const response = decodeURIComponent(data); await navigateTo(response, { redirectCode: 301, external: true, }); } });
JuanP Barba
JuanP Barba8mo ago
If it is a Nuxt API endpoint, the problem is: - when you call it from the server side, it is executed internally - I think that you see two calls because the middleware is executed again when the API endpoint is called - it seems that this behaivour is sending the response before the original call and that’s why you get “Cannot set headers after they sent to client” I didn’t see this sintax before… $../redirect/url$ Is $getApiData.fetchData executing useFetch or $fetch?
konsav
konsavOP8mo ago
useFetch
JuanP Barba
JuanP Barba8mo ago
Ok, I guess the problem is what I described. If you debug the middleware you should see that it is executed twice, one for the original call and other for the endpoint call How or where are you implementing the API endpoint? If it is internal it should be implemented at /server/api folder
konsav
konsavOP8mo ago
ok i try to delete everything and i just left the code below. The log comes twice again export default defineNuxtRouteMiddleware(async (to, from) => { console.log("Test") }); Apart from this middleware/redirect.global.js, I have also server/ middleware/ setHeaders.js that i set some headers in my project. Maybe this is the problem?
kdaniel2410
kdaniel24108mo ago
Could you use if (import.meta.server ) return?
JuanP Barba
JuanP Barba8mo ago
When you say that the log is executed twice, do you mean at server log or once at server and once at client? Yes, it could be the origin of the mentioned error.
konsav
konsavOP8mo ago
one on console and twice on terminal where should i put this condition?
Want results from more Discord servers?
Add your server