Skip to content

Commit

Permalink
fix: cannot set headers after they are sent to the client (#875)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoey-kaiser authored Sep 5, 2024
1 parent 44299ae commit d34848b
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/runtime/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { joinURL } from 'ufo'
import getURL from 'requrl'
import { sendRedirect } from 'h3'
import { sanitizeStatusCode } from 'h3'
import type { ModuleOptionsNormalized } from '../types'
import { abortNavigation, useAuthState, useNuxtApp, useRequestEvent } from '#imports'

Expand All @@ -25,18 +25,24 @@ export function joinPathToApiURL(path: string) {
* manually set `window.location.href` on the client **and then fake return a Promise that does not immediately resolve to block navigation (although it will not actually be fully awaited, but just be awaited long enough for the naviation to complete)**.
* 2. Additionally on the server-side, we cannot use `navigateTo(signInUrl)` as this uses `vue-router` internally which does not know the "external" sign-in page of next-auth and thus will log a warning which we want to avoid.
*
* Adapted from: https://github.com/nuxt/framework/blob/ab2456c295fc8c7609a7ef7ca1e47def5d087e87/packages/nuxt/src/app/composables/router.ts#L97-L115
* Adapted from: https://github.com/nuxt/nuxt/blob/d188542a35bb541c7ed2e4502c687c2132979882/packages/nuxt/src/app/composables/router.ts#L161-L188
*
* @param href HREF / URL to navigate to
*/
export function navigateToAuthPages(href: string) {
const nuxtApp = useNuxtApp()

if (import.meta.server) {
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
if (nuxtApp.ssrContext) {
// TODO: consider deprecating in favour of `app:rendered` and removing
return nuxtApp.callHook('app:redirected').then(() => {
sendRedirect(nuxtApp.ssrContext!.event, href, 302)

const encodedLoc = href.replace(/"/g, '%22')
const encodedHeader = new URL(href).toString()
nuxtApp.ssrContext!._renderResponse = {
statusCode: sanitizeStatusCode(302, 302),
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`,
headers: { location: encodedHeader },
}
abortNavigation()
})
}
Expand Down

0 comments on commit d34848b

Please sign in to comment.