Skip to content

Commit d34848b

Browse files
authored
fix: cannot set headers after they are sent to the client (#875)
1 parent 44299ae commit d34848b

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/runtime/utils/url.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { joinURL } from 'ufo'
22
import getURL from 'requrl'
3-
import { sendRedirect } from 'h3'
3+
import { sanitizeStatusCode } from 'h3'
44
import type { ModuleOptionsNormalized } from '../types'
55
import { abortNavigation, useAuthState, useNuxtApp, useRequestEvent } from '#imports'
66

@@ -25,18 +25,24 @@ export function joinPathToApiURL(path: string) {
2525
* 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)**.
2626
* 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.
2727
*
28-
* Adapted from: https://github.com/nuxt/framework/blob/ab2456c295fc8c7609a7ef7ca1e47def5d087e87/packages/nuxt/src/app/composables/router.ts#L97-L115
28+
* Adapted from: https://github.com/nuxt/nuxt/blob/d188542a35bb541c7ed2e4502c687c2132979882/packages/nuxt/src/app/composables/router.ts#L161-L188
2929
*
3030
* @param href HREF / URL to navigate to
3131
*/
3232
export function navigateToAuthPages(href: string) {
3333
const nuxtApp = useNuxtApp()
3434

3535
if (import.meta.server) {
36-
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
36+
if (nuxtApp.ssrContext) {
37+
// TODO: consider deprecating in favour of `app:rendered` and removing
3738
return nuxtApp.callHook('app:redirected').then(() => {
38-
sendRedirect(nuxtApp.ssrContext!.event, href, 302)
39-
39+
const encodedLoc = href.replace(/"/g, '%22')
40+
const encodedHeader = new URL(href).toString()
41+
nuxtApp.ssrContext!._renderResponse = {
42+
statusCode: sanitizeStatusCode(302, 302),
43+
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`,
44+
headers: { location: encodedHeader },
45+
}
4046
abortNavigation()
4147
})
4248
}

0 commit comments

Comments
 (0)