Nihar's Dev Corner

Quick tips: Persistent wrapper content in Next.js


What kind of content?

Generally what comes to mind when thinking about some content that would stay constant across all or multiple pages, is a navigation bar. It can also be a header, some branding, or a menu.

This is easy to do with the _app.js component present in Next.js projects. If you created your project with create-next-app, you would have this component too.

_app.js component

Creating a component that wraps around <Component /> will get the job done.

The wrapping component

Putting any component in the pages folder will create a new page. This component will not be a separate page on its own. So, create a new folder named components at the root of the project. Create a new file in it - Layout.js.

Project folder structure after creating components folder with wrapper component

Writing a simple header like this:

Wrapper component - Layout.js

and wrapping it around <Component /> in _app.js:

_app.js component after using the Layout.js wrapper component

it should show up on all pages. Run the project:

npm run dev

Here is a CodeSandbox. I added some styles to Layout.js and also some nav links. As you can see, the header (along with the newly added nav links or navbar) is shown on both pages.