diff --git a/docs/content/3.api/1.composables/set-response-status.md b/docs/content/3.api/1.composables/set-response-status.md new file mode 100644 index 0000000000..349993ea73 --- /dev/null +++ b/docs/content/3.api/1.composables/set-response-status.md @@ -0,0 +1,19 @@ +# `setResponseStatus` + +Nuxt provides composables and utilities for first-class server-side-rendering support. + +You can use `setResponseStatus` to set the statusCode (and optionally the statusMessage) of the response. + +`setResponseStatus` can only be called within component setup functions, plugins, and route middleware. + +```js +// Set the status code to 404 for a custom 404 page +setResponseStatus(404) + +// Set the status message as well +setResponseStatus(404, 'Page Not Found') +``` + +::alert{icon=👉} +In the browser, `setResponseStatus` will have no effect. +:: diff --git a/packages/nuxt/src/app/composables/index.ts b/packages/nuxt/src/app/composables/index.ts index cb3eb86437..92bcf1b0d1 100644 --- a/packages/nuxt/src/app/composables/index.ts +++ b/packages/nuxt/src/app/composables/index.ts @@ -9,6 +9,6 @@ export { useFetch, useLazyFetch } from './fetch' export type { FetchResult, UseFetchOptions } from './fetch' export { useCookie } from './cookie' export type { CookieOptions, CookieRef } from './cookie' -export { useRequestHeaders, useRequestEvent } from './ssr' +export { useRequestHeaders, useRequestEvent, setResponseStatus } from './ssr' export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, navigateTo, useRoute, useActiveRoute, useRouter } from './router' export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router' diff --git a/packages/nuxt/src/app/composables/ssr.ts b/packages/nuxt/src/app/composables/ssr.ts index 971a05186c..1cb916ee6a 100644 --- a/packages/nuxt/src/app/composables/ssr.ts +++ b/packages/nuxt/src/app/composables/ssr.ts @@ -15,3 +15,13 @@ export function useRequestHeaders (include?) { export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): CompatibilityEvent { return nuxtApp.ssrContext?.event as CompatibilityEvent } + +export function setResponseStatus (code: number, message?: string) { + const event = process.server && useRequestEvent() + if (event) { + event.res.statusCode = code + if (message) { + event.res.statusMessage = message + } + } +} diff --git a/packages/nuxt/src/auto-imports/presets.ts b/packages/nuxt/src/auto-imports/presets.ts index f264035903..81d94856c4 100644 --- a/packages/nuxt/src/auto-imports/presets.ts +++ b/packages/nuxt/src/auto-imports/presets.ts @@ -35,6 +35,7 @@ export const appPreset = defineUnimportPreset({ 'useCookie', 'useRequestHeaders', 'useRequestEvent', + 'setResponseStatus', 'useRouter', 'useRoute', 'useActiveRoute',