At work, on one of our projects, I ran into an issue in Nuxt 4 where a page component needs to perform different redirects via navigateTo() based on various conditions during the execution of the setup function. Something like this:
This is where the problem appears: in the end, the redirect always goes to the very last URL, i.e. in the example above the navigation ends up at /?abc=4. I dug into the documentation but couldn't find anything built-in to prevent subsequent navigateTo calls from being triggered. It seems this behavior is related to vue router.
You can't write it like this either:
In the end, the only solution that worked was introducing a boolean variable and checking it before calling navigateTo:
<template>
Some page
</template>
<script lang="ts" setup>
if (1 + 1 === 2) {
await navigateTo('/?abc=1', {
redirectCode: 302,
});
}
if (2 + 2 === 4) {
await navigateTo('/?abc=2', {
redirectCode: 302,
});
}
if (3 + 3 === 6) {
await navigateTo('/?abc=3', {
redirectCode: 302,
});
}
if (4 + 4 === 8) {
await navigateTo('/?abc=4', {
redirectCode: 302,
});
}
</script>
This is where the problem appears: in the end, the redirect always goes to the very last URL, i.e. in the example above the navigation ends up at /?abc=4. I dug into the documentation but couldn't find anything built-in to prevent subsequent navigateTo calls from being triggered. It seems this behavior is related to vue router.
You can't write it like this either:
if (1 + 1 === 2) {
await navigateTo('/?abc=1', {
redirectCode: 302,
});
return; // not allowed in script setup
}
In the end, the only solution that worked was introducing a boolean variable and checking it before calling navigateTo:
let isAlreadyRedirected = false;
if (1 + 1 === 2) {
await navigateTo('/?abc=1', {
redirectCode: 302,
});
isAlreadyRedirected = true;
}
if (!isAlreadyRedirected && 2 + 2 === 4) {
await navigateTo('/?abc=2', {
redirectCode: 302,
});
isAlreadyRedirected = true;
}
if (!isAlreadyRedirected && 3 + 3 === 6) {
await navigateTo('/?abc=3', {
redirectCode: 302,
});
isAlreadyRedirected = true;
}
if (!isAlreadyRedirected && 4 + 4 === 8) {
await navigateTo('/?abc=4', {
redirectCode: 302,
});
isAlreadyRedirected = true;
}
Once again: this is the only thing that solved the problem for me. If you have any other solution, please let me know.