Skip to content

Instantly share code, notes, and snippets.

@iamuteti
Forked from justin-schroeder/externalRedirect.ts
Created April 27, 2023 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamuteti/67f0caf399dffcb312e98cecc8eb0684 to your computer and use it in GitHub Desktop.
Save iamuteti/67f0caf399dffcb312e98cecc8eb0684 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.')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment