diff --git a/packages/nuxt/src/app/composables/cookie.ts b/packages/nuxt/src/app/composables/cookie.ts index 353229a197..a578b85e49 100644 --- a/packages/nuxt/src/app/composables/cookie.ts +++ b/packages/nuxt/src/app/composables/cookie.ts @@ -27,7 +27,7 @@ const CookieDefaults: CookieOptions = { encode: val => encodeURIComponent(typeof val === 'string' ? val : JSON.stringify(val)) } -export function useCookie (name: string, _opts?: CookieOptions): CookieRef { +export function useCookie (name: string, _opts?: CookieOptions): CookieRef { const opts = { ...CookieDefaults, ..._opts } const cookies = readRawCookies(opts) || {} @@ -53,7 +53,6 @@ export function useCookie (name: string, _opts?: return writeFinalCookieValue() } nuxtApp.hooks.hookOnce('app:error', writeAndUnhook) - nuxtApp.hooks.hookOnce('app:redirected', writeAndUnhook) } return cookie as CookieRef diff --git a/packages/nuxt/src/app/composables/router.ts b/packages/nuxt/src/app/composables/router.ts index 817265a7fb..d4a9852aa0 100644 --- a/packages/nuxt/src/app/composables/router.ts +++ b/packages/nuxt/src/app/composables/router.ts @@ -1,7 +1,7 @@ import { getCurrentInstance, inject, onUnmounted } from 'vue' import type { Ref } from 'vue' import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationNormalizedLoaded, RouteLocationPathRaw, RouteLocationRaw, Router } from 'vue-router' -import { sendRedirect } from 'h3' +import { sanitizeStatusCode } from 'h3' import { hasProtocol, joinURL, parseURL } from 'ufo' import { useNuxtApp, useRuntimeConfig } from '../nuxt' @@ -86,7 +86,7 @@ export interface NavigateToOptions { external?: boolean } -export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise | RouteLocationRaw => { +export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise | false | void | RouteLocationRaw => { if (!to) { to = '/' } @@ -111,17 +111,26 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na if (process.server) { const nuxtApp = useNuxtApp() - if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) { + if (nuxtApp.ssrContext) { const fullPath = typeof to === 'string' || isExternal ? toPath : router.resolve(to).fullPath || '/' - const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath) - const redirect = () => nuxtApp.callHook('app:redirected') - .then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302)) - .then(() => inMiddleware ? /* abort route navigation */ false : undefined) + const location = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath) - // We wait to perform the redirect in case any other middleware will intercept the redirect - // and redirect further. + async function redirect () { + // TODO: consider deprecating in favour of `app:rendered` and removing + await nuxtApp.callHook('app:redirected') + const encodedLoc = location.replace(/"/g, '%22') + nuxtApp.ssrContext!._renderResponse = { + statusCode: sanitizeStatusCode(options?.redirectCode || 302, 302), + body: ``, + headers: { location } + } + return inMiddleware ? /* abort route navigation */ false : undefined + } + + // We wait to perform the redirect last in case any other middleware will intercept the redirect + // and redirect somewhere else instead. if (!isExternal && inMiddleware) { - router.beforeEach(final => (final.fullPath === fullPath) ? redirect() : undefined) + router.afterEach(final => (final.fullPath === fullPath) ? redirect() : undefined) return to } return redirect() diff --git a/packages/nuxt/src/app/nuxt.ts b/packages/nuxt/src/app/nuxt.ts index 8716cd0d90..3c83b9680a 100644 --- a/packages/nuxt/src/app/nuxt.ts +++ b/packages/nuxt/src/app/nuxt.ts @@ -8,6 +8,7 @@ import { getContext } from 'unctx' import type { SSRContext } from 'vue-bundle-renderer/runtime' import type { H3Event } from 'h3' import type { AppConfig, AppConfigInput, RuntimeConfig } from 'nuxt/schema' +import type { RenderResponse } from 'nitropack' // eslint-disable-next-line import/no-restricted-paths import type { NuxtIslandContext } from '../core/runtime/nitro/renderer' @@ -61,6 +62,8 @@ export interface NuxtSSRContext extends SSRContext { renderMeta?: () => Promise | NuxtMeta islandContext?: NuxtIslandContext /** @internal */ + _renderResponse?: Partial + /** @internal */ _payloadReducers: Record any> } diff --git a/packages/nuxt/src/app/plugins/router.ts b/packages/nuxt/src/app/plugins/router.ts index 1560428b35..039fd9b893 100644 --- a/packages/nuxt/src/app/plugins/router.ts +++ b/packages/nuxt/src/app/plugins/router.ts @@ -5,7 +5,6 @@ import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig } from '../nuxt' import { clearError, showError } from '../composables/error' import { navigateTo } from '../composables/router' import { useState } from '../composables/state' -import { useRequestEvent } from '../composables/ssr' // @ts-expect-error virtual file import { globalMiddleware } from '#build/middleware' @@ -258,9 +257,7 @@ export default defineNuxtPlugin<{ route: Route, router: Router }>({ await router.replace(initialURL) if (!isEqual(route.fullPath, initialURL)) { - const event = await callWithNuxt(nuxtApp, useRequestEvent) - const options = { redirectCode: event.node.res.statusCode !== 200 ? event.node.res.statusCode || 302 : 302 } - await callWithNuxt(nuxtApp, navigateTo, [route.fullPath, options]) + await callWithNuxt(nuxtApp, navigateTo, [route.fullPath]) } }) diff --git a/packages/nuxt/src/core/runtime/nitro/renderer.ts b/packages/nuxt/src/core/runtime/nitro/renderer.ts index 5a48191660..77f3a1378b 100644 --- a/packages/nuxt/src/core/runtime/nitro/renderer.ts +++ b/packages/nuxt/src/core/runtime/nitro/renderer.ts @@ -167,7 +167,7 @@ const ROOT_NODE_REGEX = new RegExp(`^<${appRootTag} id="${appRootId}">([\\s\\S]* const PRERENDER_NO_SSR_ROUTES = new Set(['/index.html', '/200.html', '/404.html']) -export default defineRenderHandler(async (event) => { +export default defineRenderHandler(async (event): Promise> => { const nitroApp = useNitroApp() // Whether we're rendering an error page @@ -252,7 +252,12 @@ export default defineRenderHandler(async (event) => { }) await ssrContext.nuxt?.hooks.callHook('app:rendered', { ssrContext }) - if (event.node.res.headersSent || event.node.res.writableEnded) { return } + if (ssrContext._renderResponse) { return ssrContext._renderResponse } + + if (event.node.res.headersSent || event.node.res.writableEnded) { + // @ts-expect-error TODO: handle additional cases + return + } // Handle errors if (ssrContext.payload?.error && !ssrError) { diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 0c5ffe460c..eab3032392 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -34,7 +34,7 @@ describe.skipIf(isWindows || process.env.TEST_BUILDER === 'webpack' || process.e it('default client bundle size', async () => { stats.client = await analyzeSizes('**/*.js', publicDir) - expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('"94.3k"') + expect(roundToKilobytes(stats.client.totalBytes)).toMatchInlineSnapshot('"94.2k"') expect(stats.client.files.map(f => f.replace(/\..*\.js/, '.js'))).toMatchInlineSnapshot(` [ "_nuxt/entry.js", diff --git a/test/fixtures/basic/pages/navigate-to-external.vue b/test/fixtures/basic/pages/navigate-to-external.vue index f3a8b548a8..f18ac00b50 100644 --- a/test/fixtures/basic/pages/navigate-to-external.vue +++ b/test/fixtures/basic/pages/navigate-to-external.vue @@ -3,5 +3,10 @@ diff --git a/test/fixtures/basic/pages/navigate-to-redirect.vue b/test/fixtures/basic/pages/navigate-to-redirect.vue index 9e934988b7..f9a3a59eb5 100644 --- a/test/fixtures/basic/pages/navigate-to-redirect.vue +++ b/test/fixtures/basic/pages/navigate-to-redirect.vue @@ -9,4 +9,8 @@ definePageMeta({ return navigateTo({ path: '/' }, { redirectCode: 307 }) } }) +console.log('running setup') +useNuxtApp().hook('app:rendered', () => { + throw new Error('this should not run') +}) diff --git a/test/fixtures/basic/types.ts b/test/fixtures/basic/types.ts index 20ee6a1bbc..d84ed8ec5c 100644 --- a/test/fixtures/basic/types.ts +++ b/test/fixtures/basic/types.ts @@ -96,7 +96,7 @@ describe('middleware', () => { addRouteMiddleware('example', (to, from) => { expectTypeOf(to).toEqualTypeOf() expectTypeOf(from).toEqualTypeOf() - expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw | null | undefined, options?: NavigateToOptions) => RouteLocationRaw | Promise>() + expectTypeOf(navigateTo).toEqualTypeOf <(to: RouteLocationRaw | null | undefined, options ?: NavigateToOptions) => RouteLocationRaw | void | false | Promise>() navigateTo('/') abortNavigation() abortNavigation('error string')