-
-
Save iamuteti/67f0caf399dffcb312e98cecc8eb0684 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