nuxt-community / redirect-module

No more cumbersome redirects for Nuxt 2!
MIT License
312 stars 17 forks source link

Nuxt 3 support? #120

Closed avxkim closed 2 years ago

avxkim commented 2 years ago

Do you plan to support nuxt 3?

manniL commented 2 years ago

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!

avxkim commented 2 years ago

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

tobiasdiez commented 2 years ago

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}.

manniL commented 2 years ago

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

tobiasdiez commented 2 years ago

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

manniL commented 2 years ago

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

Closing here for now ☺️