Nuxt provides the setResponseStatus composable to set the status code (and optionally the status message) of the response.
This composable only works on the server and will have no effect on the client. Additionally, it can only be used in the Nuxt Content. The Nuxt context is only accessible in plugins, Nuxt hooks, Nuxt middleware, and setup functions (in pages and components).
Let's take a look at how to use it:
event
will be undefined
in the browser, so you can safely use this composable in your Nuxt content.
In my client's project, I used this composable to set the status code of the response to 410
when a product has expired. This way, the search engines will know that the product is no longer available and will remove it from the search results:
The important part here is to await the useFetch
composable to be able to read evaluate the data
value inside the script setup
tag.
StackBlitz
You can play with the code in this StackBlitz.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Run Code Once During SSR or CSR
Since Nuxt 3.9 you can use the useOnce composable to run a given function or block of code once during server-side rendering or client-side navigation.
Vue Tip: Cache Component Instances With the KeepAlive Component
KeepAlive is a built-in Vue component that allows you to conditionally cache component instances when dynamically switching between multiple components.