Enhancing the SEO of your Next.js application
Tags: nextjs, seo, webdev, frontend
Published: 2023-10-17 11:16:39

**Contents**
1. [Metadata](#metadata)
2. [Title and description](#title-and-description )
3. [Open Graph](#open-graph)     
4. [Sitemap](#sitemap)
5. [robots.txt](#robotstxt)
6. [Favicon](#favicon)
7. [Analytical tools](#analytical-tools)
8. [Additional tips](#additional-tips)

&nbsp;    
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](https://nextjs.org/docs/getting-started/installation) with app directory architecture enabled.
- Basic knowledge of React and Next.js framework are presumed  
- [GitHub example](https://github.com/Snoblomma/next-js-seo-example) is available

&nbsp;
## 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](https://nextjs.org/docs/app/building-your-application/optimizing/metadata#file-based-metadata) 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`:

```typescript
// app/layout.tsx
...
import type { Metadata } from 'next'
 
export const metadata: Metadata = {
}

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

This config allows to make metadata object [dynamic](https://nextjs.org/docs/app/building-your-application/optimizing/metadata#dynamic-metadata).

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

&nbsp; 
## 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:

```typescript
// 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 (...)
}
```    
&nbsp;  
## 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:

```typescript
// 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 (...)
}
```

Full list of `openGraph` properties can be found in [Next.js documentation](https://nextjs.org/docs/app/api-reference/functions/generate-metadata#opengraph)
&nbsp; 
### ***Bonus tip***:

You can also add a config for [Twitter card markup reference](https://nextjs.org/docs/app/api-reference/functions/generate-metadata#twitter) which will describe how link will be displayed when shared on Twitter(X):

```typescript
// 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 (...)
}
```    
&nbsp;  
## 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:

```typescript
// 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(),
		},
	];
}
```  
&nbsp;  
## 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](https://developers.google.com/search/docs/crawling-indexing/robots/create-robots-txt#create_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:

```typescript
// 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',
	};
}
```

Follow to [Next.js documentation](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots#robots-object) for full list of Robot's object properties. 
&nbsp;  
## 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](https://developers.google.com/search/docs/appearance/favicon-in-search#guidelines) when creating your favicon and add it `app/` directory.

![favicon location in app directory](https://cdn.sanity.io/images/l7j5p3xz/production/38b8e4daf876eb6b0e28cf136a6b26da8b1b340c-1103x943.png)

&nbsp; 
## 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](https://developers.google.com/search/docs/fundamentals/get-started-developers) 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](https://analytics.google.com/).    

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:**
```typescript
// 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');
			`,
			}}
		/>
	</>)
}
```
4\. **Add the tracking component to `layout.tsx`:**
```typescript
// 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>
		</>
	)
}
```

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](https://analytics.google.com/analytics/academy/).
&nbsp;  
## 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](https://www.semrush.com/blog/google-search-console/) has very detailed guide to head start with Google Search Console.
&nbsp;  
### 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.  
&nbsp;
Happy coding!