navigateTo & useRouter
Programmatic Navigation
Navigate from code with navigateTo — universal across server and client — or reach for useRouter for advanced control.
What you'll learn
- Use navigateTo with paths and objects
- Reach for useRouter for advanced navigation
- Pass query, replace, and external options
Sometimes you need to navigate from code — after a form submit, after authentication, or from a route middleware. Nuxt gives you navigateTo, a universal helper that works the same on the server and the client.
navigateTo
<script setup lang="ts">
async function onSubmit() {
const ok = await save()
if (ok) await navigateTo('/dashboard')
}
</script> A simple path is the most common case. You can also pass a route object for query strings and hashes:
await navigateTo({
path: '/search',
query: { q: 'nuxt', page: 2 },
hash: '#results',
}) Options Worth Knowing
// replace history entry (no back button breadcrumb)
await navigateTo('/login', { replace: true })
// leave the site
await navigateTo('https://example.com', { external: true })
// force a full reload of an internal route
await navigateTo('/heavy', { redirectCode: 302 }) Inside route middleware, returning a navigateTo() call performs a redirect cleanly:
// middleware/auth.ts
export default defineNuxtRouteMiddleware(() => {
const user = useUser()
if (!user.value) return navigateTo('/login')
}) useRouter for Advanced Cases
useRouter() returns the underlying vue-router instance. It exposes things navigateTo does not — back, forward, beforeEach guards, and resolved routes.
const router = useRouter()
router.back()
router.forward()
router.beforeEach((to, from) => {
console.log('Navigating', from.path, '→', to.path)
}) Rule of thumb: navigateTo for everyday navigation, useRouter only when you need its lower-level hooks.
Route Middleware →