How to add common header and footer in Nuxt

In this post, we will see how to add a common header and footer to your Nuxt application.

In your nuxt application, if you want to add the same header and footer component in all of your pages, then we have to use the layouts directory.

The layouts in nuxt act as the backbone for all the components and pages in our application. We can add content or different reusable component across our application with the help of layouts.

When a create a nuxt app, we get a default.vue layout inside our layouts directory. This layout is applied to all the pages that don’t have any layout specified.

Note:

In the new release, the layouts folder is not included in the creation of a nuxt project. However, you can create one like this layouts/default.vue in the root directory and it works fine as usual.

Once you create the file add these lines.

<template>
  <Nuxt />
</template>

Read more about the Layouts directory here: Directory Structure-Layouts

Add common Header and Footer with layouts in Nuxt

So to add a common header and footer we have to first create two components: Header.vue and Footer.vue in the component folder.

| components/
--| Header.vue
--| Footer.vue

Next, we will go to layouts/default.vue file and add the two components in it. If you don’t have the layouts folder create one with default.vue file.

<template>
  <div>
    <Header />
    <Nuxt />
    <Footer />
  </div>
</template>

We don’t have to import the components because starting from v2.13, Nuxt allows us to auto-import components.

If you want to enable the auto-import feature, go to your nuxt.config.js file and set components: true like this:

export default {
  components: true
}

Once you are done adding the components to your layouts folder, both the components will be applied across every page in your application.

Conclusion: In nuxt, to add common header and footer components, we have to add the components in our default.vue file in our layouts directory.


Related Topics:

How to Add External JS Script in Nuxt Component

Convert image to webp in nuxtjs | Image Optimization

How to add a custom static 404 error page in Nuxt?

Scroll to Top