DEV Community

Sarvesh Patil
Sarvesh Patil

Posted on • Updated on

How to optimise SEO in NextJs

In a digital world where visibility is everything, it’s crucial to optimize your website for search engine rankings. If you’re using Next.js to build your web app, this guide will show you the best practices to increase your website’s SEO. From meta tags and structured data to dynamic imports and server-side rendering, this article will help you make your Next.js app more search engine-friendly.

Introduction

Search Engine Optimization (SEO) is an essential part of web development. The goal is to make your website more visible to search engines and increase traffic to your site. While there are many factors that contribute to good SEO, optimizing your Next.js app for SEO can be a bit tricky. In this article, we will explore some of the best practices for optimizing your Next.js app for SEO.

Use Meta tags
Meta tags are HTML tags that describe the content of a webpage. They provide search engines with important information about your page, such as the title, description, and keywords. In Next.js, you can use the “Head” component to add meta tags to your pages.

  import Head from 'next/head'

    function MyPage() {
      return (
        <div>
          <Head>
            <title>My Page Title</title>
            <meta name="description" content="This is a description of my page." />
            <meta name="keywords" content="my, page, keywords" />
            <meta name="robots" content="index, follow" />
            <meta name="author" content="My Name" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          </Head>
          <p>This is my page content.</p>
        </div>
      )
    }
Enter fullscreen mode Exit fullscreen mode

The title tag is the most important meta tag for SEO, as it tells search engines what the page is about. The description tag provides a short description of the page, and the keywords tag lists the main keywords associated with the page. The robots tag tells search engine robots whether or not to index the page and whether or not to follow the links on the page. The author tag can be used to specify the author of the page, and the viewport tag specifies how the page should be scaled on different devices.

Next.js provides the Head component, which is a built-in component that allows you to set the head tags of a page. The Head component is similar to setting the head tag in React, but it has some advantages:

  1. Server-side rendering: When you use the Head component in Next.js, the head tags are rendered on the server and sent to the client as part of the HTML document. This can improve the performance of your app, as the browser can start rendering the page immediately, without waiting for JavaScript to execute.

  2. Dynamic head tags: With the Head component, you can set head tags dynamically based on the state of your app. This can be useful if you need to set different meta tags for different pages or based on user input.

  3. SEO optimization: The Head component provides a convenient way to set meta tags that can help with SEO. By setting the title, description, and keywords tags, you can provide search engines with valuable information about your page that can help it rank higher in search results.

  4. Multiple head tags: The ability to use the Head component in multiple pages and the built-in server-side rendering in Next.js makes it easier to maintain and update the head tags across a large website or web application.

Implement Structured Data
Structured data is a type of data that is organized in a specific way to help search engines understand the content of your webpage. This can improve your chances of appearing in rich snippets, which are more prominent search results that include additional information such as ratings, reviews, and images.

    import Head from 'next/head'

    function MyPage() {
      const structuredData = {
        "@context": "https://schema.org",
        "@type": "Product",
        "name": "My Product",
        "image": "https://example.com/my-product.jpg",
        "description": "This is my product description.",
        "sku": "1234567890",
        "brand": {
          "@type": "Brand",
          "name": "My Brand"
        },
        "offers": {
          "@type": "Offer",
          "url": "https://example.com/my-product",
          "priceCurrency": "USD",
          "price": "10.00",
          "availability": "https://schema.org/InStock"
        }
      };

      return (
        <div>
          <Head>
            <script
              type="application/ld+json"
              dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
            />
          </Head>
          <p>This is my page content.</p>
        </div>
      )
    }
Enter fullscreen mode Exit fullscreen mode

Optimize Images
Images can have a big impact on your website’s SEO. By optimizing your images for search engines, you can improve your chances of appearing in image search results. To optimize your images, you should make sure they are properly sized, compressed, and have descriptive file names and alt tags.

import Image from 'next/image'

    function MyPage() {
      return (
        <div>
          <h1>My Page</h1>
          <Image
            src="/my-image.jpg"
            alt="My Image"
            width={500}
            height={300}
          />
          <p>This is my page content.</p>
        </div>
      )
    }
Enter fullscreen mode Exit fullscreen mode

In this example, we’re using the next/image component to display an image on the page. We've specified the src attribute as the URL of the image file, and we've also set the alt attribute for accessibility purposes.

The next/image component also provides several benefits over using a regular img tag:

  1. Automatic optimization: The next/image component automatically optimizes images by compressing and resizing them to the appropriate size. This can reduce the file size of the image and improve the performance of your app.

  2. Lazy loading: The next/image component also supports lazy loading, which means that the image is only loaded when it becomes visible on the screen. This can improve the initial page load time and reduce the amount of data that needs to be downloaded by the user.

  3. Automatic format selection:The next/image component automatically selects the best image format based on the user's browser and device. This can improve the performance of your app by reducing the file size of the image and ensuring that it's displayed correctly on all devices.

  4. Automatic quality selection: The next/image component automatically selects the optimal image quality based on the user's device and connection speed. This can ensure that the image is displayed at the highest possible quality without sacrificing performance.

  5. Automatic caching: The next/image component automatically caches images on the server and the client, which can improve the performance of your app by reducing the number of requests to the server.

Use Dynamic Imports
Dynamic imports are a powerful feature of Next.js that can help improve your website’s performance and SEO. By using dynamic imports, you can load JavaScript code and components only when they are needed. This can help reduce the initial load time of your page, which is important for both user experience and SEO.

import dynamic from 'next/dynamic'

    const MyComponent = dynamic(
      () => import('../components/MyComponent'),
      { ssr: false }
    )

    function MyPage() {
      return (
        <div>
          <MyComponent />
          <p>This is my page content.</p>
        </div>
      )
    }
Enter fullscreen mode Exit fullscreen mode

Implement Server-Side Rendering
Server-side rendering (SSR) is a technique that can improve your website’s SEO by rendering your pages on the server before sending them to the client. This can improve the speed and performance of your website, as well as make it more search engine-friendly. In Next.js, you can use the “getServerSideProps” function to implement SSR.

    function MyPage(props) {
      return (
        <div>
          <p>This is my page content.</p>
          <ul>
            {myData.map((item) => (
              <li key={item.id}>{item.name}</li>
            ))}
          </ul>
        </div>
      )
    }

 export async function getServerSideProps(context) {
      const res = await fetch('https://api.example.com/my-data')
      const data = await res.json()

      return {
        props: {
          myData: data
        }
      }
    }
Enter fullscreen mode Exit fullscreen mode

The getServerSideProps function is a special function in Next.js that runs on the server every time a page is requested. It fetches data from an external API and passes it to the MyPagecomponent as a prop.
The MyPage component receives the myData prop and renders it as an unordered list using the map function. Each item in the list is a li element with the name property of the myData object as its content.

This example demonstrates how to implement server-side rendering (SSR) in a Next.js app. By fetching data on the server and passing it to the component as a prop, the data is available when the page is first loaded, making it more SEO-friendly than if the data were fetched client-side.

Conclusion

Optimizing your Next.js app for SEO can be challenging, but it’s worth the effort. By following these best practices, you can help search engines understand your content and improve your website’s visibility. By including meta tags, implementing structured data, optimizing images, using dynamic imports, and implementing server-side rendering, you can give your website a boost in search engine rankings.

Thank you for reading this far. Subscribe to my newsletter for posts just like this.

Subscribe | The Pen, Pixel & Profit Club

Join 1,187+ coders, entrepreneurs, and creators for a weekly newsletter featuring web dev tips, business case studies, how-to stories, writing deconstructions, and genius AI tools with usage instructions. Get inspiration and practical advice for your projects. Sign up now!

favicon sarveshh.beehiiv.com

Top comments (0)