Skip to content

Instantly share code, notes, and snippets.

@justin-schroeder
Created July 12, 2022 19:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save justin-schroeder/f583797c702155f32c9078d1add2a594 to your computer and use it in GitHub Desktop.
Save justin-schroeder/f583797c702155f32c9078d1add2a594 to your computer and use it in GitHub Desktop.
Perform an external redirect in Nuxt 3 router middleware
import { useNuxtApp } from '#app'
import { sendRedirect } from 'h3'
/**
* Performs an external redirect in a Nuxt3 route middleware. Once this Nuxt3
* pull request is merged, this function can be removed in favor of navigateTo:
*
* https://github.com/nuxt/framework/pull/5022
*
* @param url - An external url to redirect to
* @param code - An HTTP status code, 301 by default.
* @returns
*/
export default function externalRedirect(
url: string,
code = 301
): never | Promise<void> {
if (/^https?:\/\//.test(url)) {
if (process.server) {
const nuxtApp = useNuxtApp()
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
return nuxtApp.callHook('app:redirected').then(() => {
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
return sendRedirect(nuxtApp.ssrContext.event, url, code)
}
})
}
} else {
window.location.href = url
}
}
throw new Error('Cannot redirect to invalid URL.')
}
@justin-schroeder
Copy link
Author

Usage:

Create a composable file externalRedirect.ts in your composables directory. Then in your middleware, for example, some auth middleware:

| - 📁 composables
| -- 📄 externalRedirect.ts
| - 📁 middleware
| -- 📄 auth.global.ts
export default defineNuxtRouteMiddleware(async () => {
  if (!checkSomeAuth()) {
    return externalRedirect('https://www.google.com')
  }
})

@JamieDIng
Copy link

Thank you for solving my problem
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment