NextJS SEO: 13 Best Practices For Technical & On-Page SEO Using NextJS

93% of all web traffic comes from Google: if you want more customers, you need to master SEO.

At JAMstack Consulting, we work closely with our clients to understand their specific SEO needs, so we are used to optimize websites for search engines. We focus on JAMstack because we believe it's the best way to create fast, secure, and scalable websites with an exceptional user experience, and one of the biggest advantages of JAMstack with the programming framework NextJS is its ability to improve SEO via faster page load times, built-in SEO, and opportunities for more efficient content creation workflows.

In the following article, we'll cover the best practices you need to take into account to optimize your NextJS website for search engines. This is the fruit of years of experience, and it will save you hundreds of dollars on SEO audits: let's get started!

What’s SEO and Why Is It Important

SEO stands for "Search Engine Optimization". It’s the process of optimizing a website to appear higher in search engine results pages (SERPs) for specific keywords or queries―Google, Bing, or others.

This is a whole process with several moving parts―keyword research, on-page optimization, off-page optimization, technical audit, etc. But NextJS mainly helps with on-page SEO and technical SEO.

SEO is important because it helps organizations reach their target audience more effectively: the higher the business ranks in search engine results, the more likely people are to click on their website and potentially become customers when they search for a product or service related to what the business offers.

SEO can also help build brand awareness and credibility, as appearing high in search results can be seen as a sign of authority in a given industry or niche.

Crawling and Indexing

1. Use Semantic HTML

Search engines use the HTML code of a webpage to understand the content and structure of the page. If the HTML code is poorly structured and lacks semantic tags like headings, lists, and sections (nav, main, footer, header, aside, etc.), search engines tend to rank it lower in search results.

Typically, a blog page should contain an article tag. This way, online readers and bots can easily make sense of the content of the page and display it accordingly:

<article>
    <header>
        <h2>Article Title</h2>
        <p class="meta">Posted on <time datetime="2023-04-03">April 3, 2023</time> by <a href="#">Author Name</a></p>
    </header>

    <p>Article content goes here...</p>

    <footer>
        <ul>
            <li><a href="#">Category 1</a></li>
            <li><a href="#">Category 2</a></li>
            <li><a href="#">Category 3</a></li>
        </ul>
        <p>Tags: <a href="#">Tag 1</a>, <a href="#">Tag 2</a>, <a href="#">Tag 3</a></p>
    </footer>
</article>

2. Help Bot Crawlers

A robots.txt file placed in the root directory of a website prevent search engines from indexing pages that you don't want to be shown in search results. This is useful to avoid duplicate content that will hurt your rankings, protect sensitive information, or increase crawling speed:

User-agent: *
Disallow: /admin/
Disallow: /login/
Disallow: /404/
Disallow: /500/
Sitemap: https://www.example.com/sitemap.xml

An XML sitemap is a file that lists all the pages on a website that the website owner wants search engines to crawl. Without it, search engines can miss pages on a website, especially if they aren’t well-linked or if the website is new and has few external links. One of the first things you should do when you launch a new website is to create a sitemap and submit it in your Google Search Console. NextJS makes it easy to generate a sitemap with the next-sitemap package, but you can also create it manually:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://www.example.com/</loc>
    <lastmod>2022-03-30T14:20:00-05:00</lastmod>
    <changefreq>monthly</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://www.example.com/about</loc>
    <lastmod>2022-03-30T14:20:00-05:00</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  ...
</urlset>

A good URL structure helps search engines understand the content and hierarchy of your website. A well-structured URL includes keywords that describe the topic of the page, as well as parent folders containing related information. It makes navigation easier for end-users and also helps with monitoring which pages are driving more traffic. NextJS uses the file system to create the URL structure, so you can easily create a URL structure that is easy to understand and navigate for both users and search engines. For example, if you have a blog, you can create a folder called blog and then create a file for each blog post, like this:

https://www.example.com/blog/nextjs-seo

3. Don’t Forget Metadata Tags

Metadata tags provide important information about the web page that are used by search engines to showcase to their own users: title, description, social image, favicon, device properties, canonical URLs, and so on.

<title>NextJS SEO</title>
<meta name="description" content="NextJS SEO best practices" />
<meta name="keywords" content="nextjs, seo, best practices" />
<meta name="author" content="John Doe" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- Open Graph / Facebook -->
<meta property="og:type" content="website" />
<meta property="og:url" content="https://www.example.com/blog/nextjs-seo" />
<meta property="og:title" content="NextJS SEO" />
<meta property="og:description" content="NextJS SEO best practices" />
<meta property="og:image" content="https://www.example.com/images/seo.jpg" />

You can use the SEO tools in part 7 to check if your metadata tags are correctly implemented. Then, you can use the next/head package to append the metadata tags to the head of your pages:

import Head from 'next/head'

...

return (
    <Head>
        <title>My page title</title>
        <meta property="og:title" content="My page title" key="title" />
    </Head>
)

4. Nail Your Status Codes

Some status codes reflect poor user experience: 4xx URLs (Unauthorized, Forbidden, Request Timeout, Not Found) represent dead ends for crawlers and visitors. Same with 5XX server error status code. You need to either fix them or list the affected pages in your robots.txt to avoid SEO penalties.

Redirects can also hurt your website performance when there are too many, so they are best avoided. Similarly, you should avoid chain redirects caused by subdomain (www), https, or trailing slash misconfigurations.

Rendering

5. Use The Right Rendering Strategies

There are three main rendering strategies for websites built in NextJS: SSG, SSR, and CSR.

SSG (Static Site Generator) pre-generates HTML files for each page of the site. These HTML files are then served directly to the user's browser when they request the page. SSG is fast and efficient, but it can be less flexible with dynamic content than other approaches because the content is pre-generated. This is the default rendering method in NextJS.

SSR (Server-Side Rendering) means generating HTML dynamically on the server before sending it to the user's browser. SSR can be more flexible than SSG because the content is generated on the fly, but it can also be slower and more resource-intensive.

CSR (Client-Side Rendering) is when a website generates HTML dynamically in the user's browser using JavaScript. CSR can be very fast and flexible, but it can also be more challenging for search engines to crawl and index because the content is generated dynamically on the client side.

In terms of SEO, SSG and SSR are more search engine-friendly than CSR because the content is pre-generated or generated on the server side, making it easier for search engines to crawl and index the content. CSR is more resource-intensive for search engines to crawl because the content is generated dynamically in the user's browser.

In general, CSR is used for apps behind a login page, while public-facing, indexable pages are generated by SSG (blog article) or SSR when the content needs to be regularly updated (e.g dynamic message forum). NextJS also proposes Incremental Static Regeneration to get the best of both SSG and SSR. Check out our article on NextJS SSR to get a detailed breakdown.

6. Leverage Lazy Loading & Partial Hydration

Lazy loading means loading images, components, and libraries only when they are needed, rather than loading them all at once when the page loads and create bottlenecks.

Next.js supports lazy loading external libraries with import(), React components with next/dynamic, and images with next/image. We’ll talk more about images later, so let’s focus on the first two.

Import is a native Javascript function you can use to defer loading a third-party library until it’s needed:

const a_library = await import("/modules/my-module.js");

next/dynamic combines React.lazy and Suspense to implement partial hydration―unless the suspense is triggered, the component won’t load:

import dynamic from 'next/dynamic'

const DynamicHeader = dynamic(() => import('../components/header'), {
  loading: () => <p>Loading...</p>,
})

export default function Home() {
  return <DynamicHeader />
}

Measuring

7. Use SEO Tools

SEO tools are important to analyze, optimize, and track the performance of your website in search engine results. They provide the technical insights you need to fix errors in your NextJS codebase happening during indexing or rendering.

For example, Google’s Search Console provides an overview of all broken links and tells you how effective your sitemap is:

Google Search Console interface

Tools like Ahrefs offers a site audit feature to pinpoint which webpages contain broken links and where exactly, as well as a full list of improvement points for technical SEO and on-page optimization:

Ahrefs Site Audit

8. Use Web Dev Tools

Web dev tools like Google’s Lighthouse or Page Speed give you precious information regarding your core vitals, as well as metrics like accessibility and general SEO best practices.

Google lighthouse SEO score

It’s important to pay attention to and understand those metrics to improve your user experience, which in turn increases your ability to rank in search pages.

Loading Speed Optimization

9. Optimize Your Images

Images often weigh more than the actual text content of a webpage. Unoptimized, they drastically reduce loading speed, and thus your ranking potential.

NextJS proposes the next/image library to automate image format, resolution, and lazy-loading, but you’ll also need to pay attention to how you distribute your images (CDN, caching), enable accessibility (alt text, alternative image format, placeholders), and manage social card generation. For a detailed article on the topic, have a look at our dedicated article on NextJS images.

10. Minify All Assets

Search engines prioritize websites that provide a good user experience, which includes fast load times. And minifying assets is key to improving website speed, whether it’s images, HTML, CSS, or Javascript: unnecessary characters are removed and result in smaller file sizes, so less data to transfer.

We already talked about images―all you need is in the next/image library―and NextJS enables HTML compression via gzip by default. CSS and JS minification is also automated via the built-in bundler.

Content experience

11. Use Markdown

Programmatic SEO is a relatively new approach to SEO involving using software to optimize website content creation by automating repetitive tasks, such as keyword research and content writing, freeing up time and resources for other activities like researching and editing.

Using NextJS built-in Markdown support is key for programmatic SEO to avoid running into API limitations set up by headless CMS providers: just create a local script to produce your content, edit, and paste everything in your content folder. NextJS has great Markdown support.

But in a world where everyone uses AI to write, genuine content experiences are required: you can leverage NextJS’s MDX support to create unique experiences with rich web components that will hook your readers.

npm install @next/mdx @mdx-js/loader @mdx-js/react

12. Help Users Share Content

A backlink is when another website links to your website. It is seen as a vote of confidence in your content and a signal that your website is a reputable source of information. Backlinks are particularly valuable when they come from websites that are themselves considered to be authoritative and trustworthy by search engines. These high-quality backlinks can have a significant impact on search engine rankings, which is why it’s important to optimize your website to encourage readers to share your content.

The most obvious way to do this is to have social share buttons scattered in key places.

Another less known trick is to provide an embed feature using iframes―embed are considered like external links! The person embeds your content, and that’s an easy backlink for you!

Just make sure to build your iframes in a way that search bots can crawl and that doesn’t count as redundant content: use URL parameters for this!

<iframe 
    src="https://www.example.com/blog/nextjs-seo?embed=true" 
    width="560" 
    height="315" 
    frameborder="0" 
    allowfullscreen
></iframe>

13. Add RSS & Atom Feeds

Lastly, help your users read content however they like. Not only will it make easier to distribute your content to more people because they’ll actually enjoy reading it, but it’ll also encourage readers to visit the original website to get the most out of the content if you leveraged MDX.

NextJS doesn't offer a plugin to automatically generate RSS feeds from content sources, but you can use the rss package in a custom serverless function to generate an RSS feed from your content folder.

import { rss } from "rss";

export default async (req, res) => {
    const feed = await rss({
        title: "My Blog",
        description: "My blog description",
        site_url: "https://myblog.com",
        feed_url: "https://myblog.com/rss.xml",
        image_url: "https://myblog.com/logo.png",
        ...
    })

    res.setHeader("Content-Type", "text/xml");
    res.write(feed);
    res.end();
};

Hire Us

And that's a wrap: 13 best practices to crush SEO with NextJS! It can feel a bit overwhelming if building websites isn't your core business, so get in touch with us if you need help implementing these best practices. We're NextJS experts and we can help you build a fast, secure, and SEO-friendly website.