DEV Community

Cover image for Enhancing the SEO of your Next.js application
Kate
Kate

Posted on • Originally published at katepurchel.com

Enhancing the SEO of your Next.js application

Contents

  1. Metadata
  2. Title and description
  3. Open Graph
  4. Sitemap
  5. robots.txt
  6. Favicon
  7. Analytical tools
  8. Additional tips

 

With Next.js becoming more and more popular React framework, many have chosen it as a tool to build web applications.

Being mostly known for its great performance and SSR rendering abilities, it also allows for search engine optimization (SEO) support.

Although marketing and SEO is a huge knowledge field in itself, basic knowledge of it is essential for a web developer. Whether you're working on personal project or developing for a job task, it can be of a great benefit to anyone.

A few things to note regarding the tips in this article:

  • Examples below are intended to optimise your website's SEO specifically for Next.js application however the general concepts are universal.
  • Next.js 13: following code samples assume existence of working Next.js application with app directory architecture enabled.
  • Basic knowledge of React and Next.js framework are presumed
  • GitHub example is available

 

Metadata

Website metadata refers to the information embedded in the HTML code of web pages that provides structured data about the content and characteristics of a website. It is not visible to users when they view the webpage but is crucial for search engines and other online services.

Next.js with its Metadata API makes your metadata configuration especially easy end flexible.

Metadata can be configured in two ways in the Next.js project - using metadata config object or by adding special files to route segments. In the following examples we'll be using config-based metadata for simplicity purposes.

Note: it is possible to use config-based and file-based approach simultaneously, in this case file config will be prioritised.

By default, your metadata object would be located in layout.tsx:

// app/layout.tsx
...
import type { Metadata } from 'next'

export const metadata: Metadata = {
}

export default function RootLayout({
    children,
}: {
    children: React.ReactNode
}) {
    return (...)
}
Enter fullscreen mode Exit fullscreen mode

This config allows to make metadata object dynamic.

Note: you can also add metadata to different route layouts and pages

 

Title and description

Title tag is one of the most critical metadata elements. It defines the title of a web page and appears as the clickable headline in search engine results. A well-optimised title tag should accurately describe the content of the page and include relevant keywords, which can improve SEO rankings.

Meta descriptions are brief summaries that provide a concise preview of a web page's content. While they don't directly affect search rankings, well-written meta descriptions can encourage users to click on your search result, increasing your click-through rate (CTR) and indirectly improving SEO.

Both title and description can be added to metadata object:

// app/layout.tsx
...
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'My Website',
  description: 'Hey! Check out my cool website!',
}

export default function RootLayout({
    children,
}: {
    children: React.ReactNode
}) {
    return (...)
}
Enter fullscreen mode Exit fullscreen mode

 

Open Graph

Open Graph protocol allows you to control how your content appears when shared on social media
If you want everyone to see your website's title together with description and image when link is shared on social media, adding open graph tags is a way to go.

Next.js again makes it easy to configure those. You can update your metadata object like so:

// app/layout.tsx
...
import type { Metadata } from 'next'

export const metadata = {
    title: 'My Website',
    description: 'Hey! Check out my cool website!',
    openGraph: {
        title: 'My Website',
        description: 'Hey! Check out my cool website!',
        url: 'https://my-website.com',
        siteName: 'My Website',
        images: '/logo-og.svg'
    }
}

export default function RootLayout({
    children,
}: {
    children: React.ReactNode
}) {
    return (...)
}
Enter fullscreen mode Exit fullscreen mode

Full list of openGraph properties can be found in Next.js documentation
 

Bonus tip:

You can also add a config for Twitter card markup reference which will describe how link will be displayed when shared on Twitter(X):

// app/layout.tsx
...
export const metadata = {
    title: 'My Website',
    description: 'Hey! Check out my cool website!',
    openGraph: {
        title: 'My Website',
        description: 'Hey! Check out my cool website!',
        url: 'https://my-website.com',
        siteName: 'My Website',
        images: '/logo-og.svg',
    },
    twitter: {
        title: 'My Website',
        description: 'Hey! Check out my cool website!',
        images: '/logo-optimized-for-twitter-og.svg',
    }
}

export default function RootLayout({
    children,
}: {
    children: React.ReactNode
}) {
    return (...)
}
Enter fullscreen mode Exit fullscreen mode

 

Sitemap

Search engines use sitemaps to discover and index the pages on your website. A well-structured sitemap helps search engine bots navigate and crawl your site more efficiently. This can result in more of your web pages being indexed, increasing your website's visibility in search engine results.

Normally one would add sitemap.txt file to /public directory. However, Next.js provides a way to have a dynamic sitemap which will tell search engines that your website is up-to-date.

Add sitemap.tsx to app/ directory:

// app/sitemap.tsx
import { MetadataRoute } from 'next';

export default function sitemap(): MetadataRoute.Sitemap {

    return [
        {
            url: 'https://your-website.com',
            lastModified: new Date(),
        },
        {
            url: 'https://your-website.com/blog',
            lastModified: new Date(),
        },
        {
            url: 'https://your-website.com/contact',
            lastModified: new Date(),
        },
    ];
}
Enter fullscreen mode Exit fullscreen mode

 

robots.txt

This is the crucial file that instructs robots (typically search engine robots) how to crawl and index pages. It serves as a guide for search engine crawlers to determine which pages or files of a website should be crawled or not. Is consists of set of rules that are read top-to-bottom by crawlers.

Again, you can add robots.txt to your public folder or you can make it dynamic just like with example for sitemap above:

// app/robots.tsx
import { MetadataRoute } from 'next';

export default function robots(): MetadataRoute.Robots {

    return {
        rules: {
            userAgent: '*',
            allow: '/',
            disallow: '/admin'
        },
        sitemap: 'https://your-website.com/sitemap.xml',
    };
}
Enter fullscreen mode Exit fullscreen mode

Follow to Next.js documentation for full list of Robot's object properties.
 

Favicon

The website icon, also known as a "favicon" (short for "favorite icon"), is a small image or icon that appears in a web browser's tab, bookmarks, and sometimes in search results or social media previews

While the favicon itself is not a direct ranking factor for SEO, it can have an indirect impact on the user experience and brand recognition, which can, in turn, influence SEO. Good-quality icon makes your website look credible and professional.

Make sure to follow styling guidelines when creating your favicon and add it app/ directory.

favicon location in app directory

 

Analytical tools

Obviously, there no point to implement SEO concepts without actually tracking how and to what extent they work. This is where analytical tools step in.

There are countless analytical tools and services to choose from that can track your website's performance, but Google, being the most popular engine for 16 years straight, provides the most popular ones.

Google Analytics

Google Analytics is a powerful web analytics service that allows website owners and marketers to track and analyse various aspects of their website's performance and user behaviour.

Let's see how we can integrate it into our Next.js app.

1. Create a Google Analytics Account: If you don't already have a Google Analytics account, sign up for one at Google Analytics.

2. Create a New Property: After creating an account, set up a new property for your Next.js website in your Google Analytics account. You'll receive a unique Tracking ID (G-XXXXXXXXX) that you'll need to integrate into your Next.js application.

3. Create Google Analytics component:

// app/components/GoogleTag.tsx
import Script from 'next/script'

export default function GoogleTag() {
return (
    <>
        <Script async strategy="afterInteractive" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX" />
        <Script 
            id="google-analytics" 
            strategy="afterInteractive" 
            dangerouslySetInnerHTML={{
            __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);} 
                gtag('js', new Date()); 
                gtag('config', 'G-XXXXXXXXXX');
            `,
            }}
        />
    </>)
}
Enter fullscreen mode Exit fullscreen mode

4. Add the tracking component to layout.tsx:

// app/layout.tsx
import '@/app/globals.scss'
import GoogleTag from '@/components/GoogleTag'

...

export default function RootLayout({
    children,
}: {
    children: React.ReactNode
}) {

return (
        <>
            <GoogleTag />
            <main>
                {children}  
            </main>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

Voila! You should see your websites clicks on your Google Analytics dashboard. You can learn more about reports and automations in one of Google's free courses.
 

Additional tips

Google Search Console

Although not requiring special setup for Next.js, Google Search Console is an excellent free web service provided by Google that allows you to monitor, manage, and optimise how your website appears in Google search results.

Semrush blog has very detailed guide to head start with Google Search Console.
 

Ensure your app is mobile friendly

Considering that 50 to 60% internet traffic is coming from mobile devices, mobile friendly-website is no longer a bonus but rather a requirement. Make sure your website is responsive and mobile-friendly. You don't want visitors to drop off because the call-to-action button is unreachable or the text is being cut off/overflown.

On top of that, mobile optimisation can positively impact your search engine rankings, making it easier for users to find your site in the first place.

Build high-quality backlinks

Try to get other high-quality websites that are relevant to your field link to yours. This will help increase your website's authority and improve its ranking in search results.

There are countless possibilities to this, you can post links on your social media, collaborate with others in your field for link exchange etc.

Update your content regularly

Search engines generally favour websites that regularly update their content. Fresh content can help improve your search engine rankings, making it easier for potential visitors to find your site.

 
Happy coding!

Top comments (1)

Collapse
 
leandro_nnz profile image
Leandro Nuñez

Perfectly explained. Thanks for sharing!