Created
July 12, 2022 19:36
-
-
Save justin-schroeder/f583797c702155f32c9078d1add2a594 to your computer and use it in GitHub Desktop.
Perform an external redirect in Nuxt 3 router middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Usage:
Create a composable file
externalRedirect.ts
in your composables directory. Then in your middleware, for example, some auth middleware: