posts
/how-to-use-seo-with-nextjs

How to use SEO with Next.js

Published Jan 3, 2022

post image

For SEO we will going to use next-seo. This package will help us create SEO easily wether we want it in a page-to-page basis or available globally throughout our Next.js app.

Firstly, let's add the package using npm:

copy
npm install --save next-seo

or with yarn:

copy
yarn add next-seo

Now if you want your SEO in a page-to-page basis, you can simply do it like this, just like in the Readme of next-seo.

copy
1import { NextSeo } from "next-seo";
2
3const Page = () => (
4  <>
5    <NextSeo
6      title="Simple Usage Example"
7      description="A short description goes here."
8    />
9    <p>Simple Usage</p>
10  </>
11);
12
13export default Page;

This is nice, but I prefer to use <DefaultSeo /> and attach it in the _app.js. So we can simply pass SEO object to _app.js using props from each page. In Next.js we can pass the props from within the getStaticProps or getServerSideProps.

copy
1// _app.js
2import React from "react";
3import { DefaultSeo } from "next-seo";
4
5function MyApp({ Component, pageProps }) {
6  const SEO = {
7    ...(pageProps.seo != null ? { ...pageProps.seo } : {}),
8    defaultTitle: "Some default title if pageProps.seo object is null",
9  };
10
11  return (
12    <React.Fragment>
13      <DefaultSeo {...SEO} />
14      <Component {...pageProps} />
15    </React.Fragment>
16  );
17}
18
19export default MyApp;

Then inside the page:

copy
1// some /page/name.js
2export default function Page({ props }) {
3  // ... some page logic
4}
5
6export async function getStaticProps({ params }) {
7  return {
8    props: {
9      // here we pass the seo object to _app.js
10      seo: {
11        title: "Page Title",
12        description: "Page Description",
13      },
14    },
15  };
16}

That's it! You now have SEO working in your Next.js app. 🥳

Further reading into next-seo documentation to know more about the SEO object scheme for your needs.

Copy Link