NUXT server page navigateTo redirect
Hello!
I have a Nuxt page in /pages directory. Say /buy/index.server.vue
with content
<script setup lang="ts">
// Some API calls using useFetch, and then based on API calls results, redirect user to different urls
//.....
await navigateTo('https://google.com', { external: true });
</script>
When I goto localhost/buy url, it throws 302 Server error.
But when I remove .server from file, it works as expected i.e. I am redirected to google.
I was hoping that .server will only run this on server and redirect user accordingly.
2 Replies
Hi @dan1234. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
I understand your issue with server-side redirects in Nuxt. The behavior you're experiencing is expected based on how server components and navigation work in Nuxt.
When you use a
.server.vue
component, the code runs exclusively on the server. When you call navigateTo
with an external URL from a server component, it attempts to perform a server-side redirect by setting HTTP headers. This is why you're seeing a 302 status code - it's actually a redirect status code, not an error.
The issue is that server-side redirects work differently than client-side redirects. On the server, redirects are handled by sending a Location
header to the browser, which then makes a fresh request to the new location. As mentioned in the Nuxt documentation:
Any redirection on the server will result in a Location:
header being sent to the browser; the browser then makes a fresh request to this new location. All application state will be reset when this happens, unless persisted in a cookie.
Nuxt Lifecycle
When you remove the .server
suffix, the component runs on both server and client, but the navigation happens on the client side, which works as expected.
For external redirects in server components, you might want to consider using Nitro's sendRedirect
function instead of navigateTo
. However, this would need to be done in a server route rather than a page component.
Alternatively, if you want to stick with your current approach, you could:
1. Keep using a regular page component (without .server
) and perform your API calls with useFetch
2. Use navigateTo
for the redirect based on the results
This way, the initial rendering happens on the server, but the actual navigation occurs on the client, which should work as expected for external URLs.
GitHub: PR #27472 and PR #26712 show that there have been improvements to how navigateTo
handles external URLs and encoding, which might be relevant to your case.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@560924716270092300> Kapa.ai is still learning and improving, please let me know how I did by reacting below.