How to create 404 missing page in Nuxt using Composition API

Nuxt guide logo

Nuxt 2

Create a Vue file under /layouts folder, name it as error.vue which consist of the below code.

in the template

                                <template>
  <section>
    <!--
      error.message will contain a message
      from the original page the error was sent from
    -->
    {{ error.message }}
  </section>
</template>
                            

inside the script tag

                                
                                        <script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api';

export default defineComponent({
props: ['error'],
setup(props) {
  // (optional) Update page title to be the error message
  const { title } = useMeta();
    title.value = props.error.message;
  },
});
</script>
                                    
                            

Where ever something is invalid - can be ID or page slug - that page needs to return a HTTP response status codes , in this case we will send 404 status.

                                
                                        <script lang="ts">
import { defineComponent, useContext } from '@nuxtjs/composition-api';

export default defineComponent({
setup() {
  const { error } = useContext();
  error({
    statusCode: 404,
    message: 'Page you are looking for is not exist',
  });
});
</script>
                                    
                            

Nuxt 3

Create a Vue file and name it as error.vue at the root of your project folder (next to nuxt.config.ts). This page will have an error props that contain message and status code.

In the error.vue template

                                <template>
  <section>
    <h1>The page you are looking for is not exist.</h1>
    <button @click="handleError">Go back home</button>
  </section>
</template>
                            

In the script tag

                                
                                        <script setup lang="ts">
const props = defineProps({ error: Object });
// handleError will be attached to a button when click it will redirect to home page
const handleError = () => clearError({ redirect: '/' });
</script>
                                    
                            

Where ever something is invalid, that page needs to be sending an error status code and/or a message.

                                
                                        <script setup lang="ts">
const error = useError();
if (checkSomethingIsValidORNot) {
  error.value = {
    statusCode: '404',
    message: 'Page not found',
    url: '/',
    statusMessage: 'Page not found',
    description: 'Page not found',
  };
  
  throw createError({ statusCode: 404, statusMessage: 'Page Not Found' });
}
                                    
                            
Previous post How to use Markdown content in Nuxt 2 and Typescript
Next post Separating SCSS style from Vue template