nuxt-community / redirect-module

No more cumbersome redirects for Nuxt 2!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nuxt 3 support?

avxkim opened this issue · comments

Do you plan to support nuxt 3?

https://github.com/nuxt/framework/discussions/560 should cover that one day.

But if demand is there I'll migrate the module to Nuxt3 for sure!

I think it would have a lot of demand soon :)

This module works for me in nuxt3:

import { addPluginTemplate, defineNuxtModule } from '@nuxt/kit'
type Redirect = { from: string; to: string; external?: boolean }

// For some reason nuxt converts an array as module option to an object of the form { 0: '...', 1: '...' }
export type ModuleOptions = {
  [key: string]: Redirect
}

export default defineNuxtModule<ModuleOptions>({
  meta: {
    configKey: 'redirects',
  },
  setup(moduleOptions, _nuxt) {
    addPluginTemplate({
      filename: 'redirects.mjs',
      write: true, // for easier debugging
      getContents: () => `
      import { createRouter } from 'radix3'
      export default defineNuxtPlugin(nuxt => {
        const redirects = createRouter()
        const moduleOptions = ${JSON.stringify(moduleOptions)}
        Object.values(moduleOptions).forEach(({ from, to, external }) => {
          redirects.insert(from, { to, external })
        })
        addRouteMiddleware((to, _from) => {
          const redirect = redirects.lookup(to.path)
          if (redirect) {
            return navigateTo(redirect.to, { external: redirect.external })
          }
        })
      })`,
    })
  },
})

Usage is similar to the existing redirect module (although not all features are supported). In particular, add your redirects in nuxt.config.ts as an array of entries the form {from: '/abc', to: '/cde', external: true/false}.

@tobiasdiez This seems like a nice option! I'd probably pair that with equivalent nitro middleware too 😋

Can you please share your nitro Middleware. I also looked into this but couldn't find a working solution. Thanks!

Nuxt 3 support will be given via Nitro itself, mainly via Route Rules.

Closing here for now ☺️