·
1 min read

Nuxt Tip: Change Status Code of the Response

Nuxt Tip: Change Status Code of the Response Image

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:

const event = useRequestEvent() if (event) { setResponseStatus(event, 404, 'Page Not Found') }

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:

ProductPage.vue
<script setup lang="ts"> const { data, error } = await useFetch('/api/product'); const event = useRequestEvent(); if (event && data.value?.isGone) { setResponseStatus(event, 410); } </script>

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.