<script setup lang="ts">// Passing 'to' as a stringawait navigateTo('/search')// ... or as a route objectawait navigateTo({ path: '/search' })// ... or as a route object with query parametersawait navigateTo({ path: '/search', query: { page: 1, sort: 'asc', },})</script>
export default defineNuxtRouteMiddleware((to, from) => { if (to.path !== '/search') { // Setting the redirect code to '301 Moved Permanently' return navigateTo('/search', { redirectCode: 301 }) }})
When using navigateTo within route middleware, you must return its result to ensure the middleware execution flow works correctly.The following implementation will not work as expected:
export default defineNuxtRouteMiddleware((to, from) => { if (to.path !== '/search') { // This will not work as expected navigateTo('/search', { redirectCode: 301 }) return }})
In this case, navigateTo will be executed but not returned, which may lead to unexpected behavior.
The external parameter influences how navigating to URLs is handled:
Without external: true:
Internal URLs navigate as expected.
External URLs throw an error.
With external: true:
Internal URLs navigate with a full-page reload.
External URLs navigate as expected.
<script setup lang="ts">// Will throw an error;// navigating to an external URL is not allowed by defaultawait navigateTo('https://nuxt.com')// Will redirect successfully with the 'external' parameter set to 'true'await navigateTo('https://nuxt.com', { external: true,})</script>
<script setup lang="ts">// Will open 'https://nuxt.com' in a new tabawait navigateTo('https://nuxt.com', { open: { target: '_blank', windowFeatures: { width: 500, height: 500, }, },})</script>