redirect-module icon indicating copy to clipboard operation
redirect-module copied to clipboard

Nuxt 3 support?

Open avxkim opened this issue 3 years ago • 5 comments
trafficstars

Do you plan to support nuxt 3?

avxkim avatar Sep 03 '22 17:09 avxkim

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!

TheAlexLichter avatar Sep 04 '22 19:09 TheAlexLichter

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

avxkim avatar Sep 08 '22 13:09 avxkim

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 avatar Sep 24 '22 11:09 tobiasdiez

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

TheAlexLichter avatar Sep 24 '22 11:09 TheAlexLichter

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

tobiasdiez avatar Sep 24 '22 15:09 tobiasdiez

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

Closing here for now ☺️

TheAlexLichter avatar Nov 04 '22 10:11 TheAlexLichter