Back

SEO Tips for Next.js sites

SEO Tips for Next.js sites

SEO stands for Search Engine Optimization. It is the process of optimizing a website’s technical configuration, content relevance, and link popularity so that its pages are easier to find, more relevant and popular to user search queries, and, as a result, SERP (Search Engine results page) rank them higher. I believe you know SERP, which has grown in importance due to business requirements. We also understand how SERP works and what they require to increase your website traffic. And, as a developer, I understand how important SERP is for any company’s online presence. It is our responsibility to ensure that our tools aid in the effort of appearing prominently on search engine results pages.

And, because React has been the most popular JavaScript framework, these tools are almost certainly related to it or React frameworks like Next.js. But how can we ensure that our React applications are SEO-friendly and understandable to our favorite web robot crawlers? That’s precisely what we’ll look into today. How Next.js can help our React-powered SPA(single page application) improve its Search Engine Optimization.

In this article, I will review some key points to consider when working with Next.js.

What are Next.js and its features?

Next.js is an open-source react framework tool created by Vercel. It enables you to use React to create server-side rendering and static web applications. It’s an excellent tool for creating your Next.js website. It has many great features and benefits that make Next.js your first choice for developing your next web application. Next.js helps you to build full-stack web applications without worrying about the front-end and back-end. Next.js has stunning features that will make your app more productive and interactive.

These are the details:

  • Built-in CSS support
  • Image Component and Optimization
  • Static-file serving
  • Typescript support
  • Supported Browser and features
  • Fast Refresh support
  • Meta Tags and Routing
  • Data Fetching

What are SPA and the challenges with SPA SEO?

A single-page application (SPA) is a web application or website that interacts with the user by dynamically changing the current web page data with the new data from the server. This way, the browser updates the data instead of the entire web page. Generally, you may be more aware of a server-side method, in which each page of your web app has its route, i.e., page URL, but with a SPA, you have a single route that uses JavaScript to load up the entire web app in the browser using JavaScript.

Let’s look at a small example of a React application. While developing your react apps, you may have come across React, which uses mount to attach to a specific page element. You can accomplish this by serving a page to your user, such as index.html, and the browser will perform the mount action based on your command.

React_homepage

When the web page loads, React takes over and allows you to do whatever you wish. Anyhow it’s providing simple things for the user to interact with or giving some routing mechanism to change pages. In this scenario, the entire experience began with that single page.

When it comes to single-page applications, SEO optimization is a critical and challenging component. Assume your website’s entry point is index.html, and Google searches for the web page’s URL. They can only see the first web page’s content and metadata.

I’ll go over some of the SEO with SPA points here:

  • Search Engine Optimisation: Search engine optimization is the process of increasing the quality and quantity of website traffic from search engines to a web page.
  • Security: Single-page applications are especially vulnerable to Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) attacks. To deflect such attacks, you must be extra careful when developing SPAs apps.
  • Performance: Keep performance in mind as you build and add features to your app. If you are experiencing performance problems, you should first profile the app. The Webkit inspector includes a profiler that can generate a detailed report for CPU, memory, and rendering bottlenecks.

With these challenges, we begin to lose our competitive advantage when attempting to leverage one of the web’s most significant potential traffic sources.

Why SEO is Important?

Search Engine Optimization allows the search engine to understand better and read the content. So that it understands what your website is about.

These are essential steps to attract as many people as possible to your website. The goal of people searching the internet is to find something helpful for them, which could be the content you’re trying to share through websites. More visitors equals more potential sales for your company’s growth.

Today search engines are getting smarter due to teams’ hard work like Google and Duck Duck Go. While they may be able to guess what your content is about or what products your company sells, they are limited by the information you provide and how you can provide it.

SPAs are difficult to crawl because they do not provide much information about the content that Google is looking for. In this way, you miss big opportunities; people cannot find your content.

How does Next.js help with SEO?

Next.js is a React web framework that sits on top of React, providing features that can take our applications to the next level. Another option would be to use .html files for all of our pages. Instead of loading from the initial homepage, React would mount the application and content for that specific page (e.g., About page, Contact page) for each visited page.

Next.js has a few different techniques and APIs that developers can use to ensure we’re providing as much SEO value as possible.

  • Static-side generation:- Static-side generation is the practice of pre-rendering some or all of the pages of a website/application ahead of the browser at compile time known as static site generation (SSG). The index.html file would contain the majority, if not the entirety, of the experience that will be loaded in the browser. Static Generation tools, such as Next.js, attempt to render that page as it would in the browser, but at compile time. This allows us to serve the entire content on the first load. During this process, the scripts continue to hydrate the page but with fewer or no changes.
  • Server-Side Rendering: In next.js, if pages use the server-side rendering, a page is generated for each request. To use Server-side Rendering on a page, export the async function getServerSideProps. The server will call this function on every request.

Assume that your page must pre-render frequently updated data (fetched from an external API). You can use getServerSideProps to retrieve this data and pass it to Page, as shown below:

function Page({ data }) {
  // Render data...
}
// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`);
  const data = await res.json();
  // Pass data to the page via props
  return { props: { data } };
}

export default Page;

As you can see, getServerSideProps is similar to getStaticProps; however, getServerSideProps is called on every request rather than at build time.

Check out the Data Fetching documentation to learn more about how getServerSideProps works.

  • Header Component: Whatever option you choose, one of the most difficult aspects of using tools like React to build a web page is that these applications are mounted into an HTML page. This means that you don’t have direct access to places like a website without using additional tools. It’s traditionally where a lot of important metadata for describing your content to search engines resides.

Fortunately, Next.js includes a Head component out of the box that we can use to ensure that all of our pages include the important details that need to be rendered into our page. To make it work, first import the head component, then include it as a child of a Next.js page. Then you can add whatever you want to the Head.

Here, you can see the relator website has used the meta tags for SEO

function HomePage() {
  return (
    <div>
      <Head>
        <title>realtor.com®|Homes for Sale, Apartments;Houses for Rent</title>
        <meta
          name="description"
          content="Search homes for sale, new construction homes, apartments, and houses for rent. See property values. Shop mortgages."
        />
        <meta property="og:URL" content="https://www.realtor.com" />
        <meta
          property="og:title"
          content="realtor.com® | Homes for Sale, Apartments &amp; Houses for Rent"
        />
        <meta
          property="og:description"
          content="Search homes for sale, new construction homes, apartments, and houses for rent. See property values. Shop mortgages."
        />
      </Head>
    </div>
  );
}

Next.js will allow that metadata and do the hard work of lifting it to the right location in your HTML document when the page is rendered.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Building SEO-friendly Next.js applications (with examples)

We’ll begin by creating a React application from scratch, then add metadata to our pages with the Next.js Head component.

Because Next.js allows us to manage that metadata across multiple pages, we’ll look at how we can customize it for new static pages and generate that metadata for dynamic pages.

  1. Using Next.js to create a new React app.

We can begin by using create next app to create a new Next.js application from scratch.

Run the following command in your terminal:

yarn create-next-app demo-seo-app
npm create-next-app demo-seo-app

When you run this command, Next.js will create a local copy of a starter application template and install the necessary dependencies to get the project up and running. When it’s finished, navigate to that directory:

cd demo-seo-app

After that, you can start your next.js development server by typing the following command:

npm run dev or yarn dev

When Next.js is loaded, it will notify you that the server is up and running at http://localhost:3000. You can see your new Next.js site if you open that in your browser!

Nextjs-homepage

  1. Updating the SEO metadata on the Next.js homepage.

When you create a new Next.js application, the framework starts with a homepage that includes some sample content. Furthermore, it comes with the Next.js Head component out of the box, which is first imported at the top of the file:

import Head from 'next/head'

In addition, here are a few examples of metadata:

<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>

In this case, we’re creating our Head component available before adding a title, description, and favicon. We can see this metadata as well as other things that Next.js manages for us if we view the source code of this page in the browser:

nextjspage_with_metatags

We can even change the image for our favicon, which is located at public/favicon.ico. We could also include more fields, such as the title and description that we saw earlier:

<Head>
<title>Shopping Store</title>
<meta name="description" content="Come to our store with maximum discount" />
<meta property="og:title" content="Shop Store" />
<meta property="og:description" content="Come to our store with maximum discount" />
<meta property="og:URL" content="https://myclothingstore.com/" />
<meta property="og:type" content="website" />
<link rel="icon" href="/favicon.ico" />
</Head>

This allows us to design our page’s metadata exactly how we want it.

  1. Next.js generates SEO metadata for dynamic page

As previously stated, one of the primary advantages of Next.js for SEO is the ability to provide direct links to individual pages. It allows us to customize the metadata on that page for Google and our visitors. To do so, we can create a new page and see how it works!

Make a new file called about.js in the pages directory. Add the following to pages/about.js:

import styles from "../styles/Home.module.css";

export default function About() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}> About My Shopping Store</h1>
      </main>
    </div>
  );
}

This will generate a new “About ” page at the /about path. We can test this by going to http://localhost:3000/about in our browser.

About Page

While this page is straightforward, it is clear that we could easily create a new page that can be accessed directly via the URL.

We keep the same SPA capabilities because we’re still inside React, but we can also create content specific to each page without sacrificing SEO or user experience.

Let’s add the Next.js Head component to see how this works with metadata. Import the Head component at the top of pages/about.js by adding:

import Head from "next/head";

<Head>
  <title>About - My Shopping Store</title>
  <meta name="description" content="The story behind My Clothing Store!" />
  <meta property="og:title" content="About - My Clothing Store" />
  <meta
    property="og:description"
    content="The story behind My Clothing Store!"
  />
  <meta property="og:URL" content="https://myclothingstore.com/about" />
  <meta property="og:type" content="website" />
  <link rel="icon" href="/favicon.ico" />
</Head>;

Open our browser and inspect the source code; we can see that our About page displays the metadata specific to that page.

About page metadata

We can help Google understand what each of our first pages is about by utilizing Next.js’s ability to have multiple pages with custom content and metadata!

  1. Next.js generates SEO metadata for dynamic pages

We create a new file with the desired route and generate a React component with the content. Dynamic pages, on the other hand, are more difficult because they are dynamic.

While we won’t go into great detail about how dynamic pages work, we can walk through a simple example to see how we can dynamically manage the metadata on our page. Let’s begin by making a new folder called products, and a new file called [productId].js within that folder.

Inside of products/[productId].js add the source code:

import styles from "../../styles/Home.module.css";

export default function Product({ productId, title }) {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>{title}</h1>
        <p>Product ID: {productId}</p>
      </main>
    </div>
  );
}

export async function getStaticProps({ params = {} } = {}) {
  return {
    props: {
      productId: params.productId,
      title: `Product ${params.productId}`,
    },
  };
}

export async function getStaticPaths() {
  const paths = [...new Array(5)].map((i, index) => {
    return {
      params: {
        productId: `${index + 1}`,
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
}

In this example, we’ll use getStaticPaths to create a route inside Next.js to demonstrate how we can manage our dynamic metadata. Paths are typically built based on dynamic content, such as API requests or data files.

Here’s a quick rundown of what we’re up to:

  • We’re making a new page with similar content to Step 2.
  • We’re defining getStaticProps, which takes an argument that includes a parameter’s dynamic value. This parameter is named after the file we created, productId.js.
  • When that parameter value is received, we define a simple title and productId, which will be passed as props to our page component.
  • We’re going to define getStaticPaths, which will use a new array to simulate a list of dynamic data.

Save that file, restart your development server, and now open /products/5 at http://localhost:3000/products/5 in your browser.

product page

Now, we are using the dynamic data on our first page; we can also use the same data to create metadata.

As before, begin by importing the Next.js Head component at the top of the page:

import Head from 'next/head'

Then add the following to the source code on the page component of pages/[productId].js

<Head>
  <title>{title} - Shop Store</title>
  <meta name="description" content={`Learn more about ${title}`} />
  <meta property="og:title" content={`${title} - Shop Store`} />
  <meta property="og:description" content={`Learn more about ${title}`} />
  <meta
    property="og:URL"
    content={`https://fakestoreapi.com/products/${productId}`}
  />
  <meta property="og:type" content="website" />
  <link rel="icon" href="/favicon.ico" />
</Head>;

We’re adding metadata to the Head component in this snippet. This time, however, we’re dynamically setting the metadata for all of our values by using our product’s title and product ID.

We can see in the browser that our Head has those dynamic values!

display dynamic value

Tips to improve our SEO Next.js sites

The Next.js Head component, in conjunction with its page creation strategies, can assist us in carefully crafting our experience for both our visitors and Google. Still, there is more we can do to ensure that our SEO actions are always optimized.

  1. To Analyze and monitor with Google Webmaster Tools and web. dev One of the first things we can do is run a test to ensure that our website or application covers the fundamentals. Fortunately, Google offers some free tools to help with this, such as the Search Console and web.dev, which will also test performance and accessibility. SEO is also aided by performance and accessibility.

  2. Adding a sitemap Including a sitemap on your website is probably not as important as it once was. Google can crawl your site fairly quickly, but it’s still an excellent way to ensure that all your content is accessed. While Next.js does not support this out of the box, some plugins can help, such as the Next.js Sitemap Generator, or a custom approach, such as the one I added to my Next.js WordPress Starter.

Conclusion

Today Google SERP has become much smarter in recent years due to its algorithm. As a result, as business owners or developers, we should know SERP and what elements are required on the first page to create unique content. SEO is essential for driving traffic to your website/app and your business, and Google SERP also influences how your website appears on the first page.

With Next.js, tools provide solid foundations for providing an excellent experience to our customers and the search engines that crawl our websites.

A TIP FROM THE EDITOR: Learn more about rendering and SEO with our Pre-rendering Techniques in Next.js for React article.