Nuxt-Typed-Router

image Provide a type safe router to Nuxt with auto-generated typed definitions for route path, name and params with nuxt-typed-router.

  • Supports all programmatic navigation utils (NuxtLink, useRouter, navigateTo, useRoute, useLocalePath, etc...)
  • Supports optional params and catchAll routes
  • Autocompletes routes paths, names and params
  • Throw error if route path is invalid
  • Out of the box i18n support
  • Supports routes extended by config and modules

image-1

Documentation

View documentation here

Demo

Play with it on Stackblitz

Tutorial Video

Made by LearnVue

https://www.youtube.com/watch?v=jiYoAiFb71Y&t

Compatibility:

Quick start

For Nuxt 3

yarn add -D nuxt-typed-router
# or
npm install -D nuxt-typed-router
# or
pnpm install -D nuxt-typed-router

Nuxt 2 legacy (not maintained)

Nuxt 2 version is no longer maintained, but still available in nuxt2 branch It only has route name autocomplete functionnality

yarn add -D nuxt-typed-router@legacy
# or
npm install -D nuxt-typed-router@legacy

Configuration

Register the module in the nuxt.config.ts, done!

export default defineNuxtConfig({
  modules: ['nuxt-typed-router'],
});

Example Usage

pages/login.vue

When a route has no params defined, the params property will not even be available as an option in the router.

router.push('/login/bar'); // Error! 
router.push({name: 'login', params: {foo: 'bar'}}) // Error! 

router.push('/login'); // Good! 
router.push({name: 'login'}) // Good! 

pages/user/[id].vue

When a route has a required param defined, navigating exactly to this route will throw an error if you don't provide a params property or if you put a wrong param.

router.push({name: 'user-id'}) // Error! 
router.push({name: 'user-id', params: {bar: 'baz'}}) // Error! 
router.push('/user') // Error! 

const id = "ey7878"
router.push(`/user/${id}`) // Good! 
router.push({name: 'user-id', params: {id}}) // Good! 

router.push(`/user/${id}/baguette`) // Error! 

For resolved routes, the params property will be available and correctly typed.

const route = useRoute();
if (route.name === 'foo') {
  console.log(route.params.baz); // Error! 
  console.log(route.params.foo); // Good! 
}