Please Signin

Welcome to Arun's Blog , By signing in, you'll enjoy a seamless journey and save your preferences

Search Engine Optimization On NextJs

Welcome to the comprehensive guide on Search Engine Optimization (SEO) for Next.js. In this blog, we'll dive deep into the strategies and techniques you need to boost your Next.js website's visibility and crawlability on on search engines.

Search Engine Optimization On NextJs

Lets bring our nextjs site on google

Table Of Content

By following all the techniques below, we can optimize our web application to get better visibility for search engine crawlers.

  • Server Side Rendering (SSR)
  • Meta Tags
  • Sitemap.xml
  • Robots.txt
  • Schema Markup (ld+json)
  • Caching
  • Image Optimization

lets deep dive into the comprehensive guide on Search Engine Optimization (SEO) for Next.js.

Server Side Rendering (SSR)

Server side rendering is a very popular technique in web development where data getting fetched in the server only and the final response comes to the client is a fully baked html that directly gets pained in the browser window and it not only improves user experience also it enables great visibility of the content to the search engine crawlers.

How to do server side rendering in NextJs?

1   // page.jsx

2  

3   const fetchData = async () => {

4   const response = await fetch(url);

5   const json = await response.json();

6   return json;

7   }

8  

9   const page = async () => {

10   const data = await fetchData();

11  

12   return (

13   <div>

14   {data.map((item) => (<p> {item.title} </p>))}

15   </div>

16   )

17   }

18  

19   export default page;

Since NextJs supports React Server Component, we will able to make a top level fetch request and block the rest code execution untill the data gets fetched. Through this the entire html goes to the client an it significantly improves visibility of the content in the search engines.

How does it make a difference?

To understand the differences lets understand how crawlers read our website. Crawlers usually reads the page source of the html page, we can see the page source by pressing ctrl+u 

observe the below image for better understanding

Different page source
Different page source

Different page source

As you can see both code generates the same output on the browser but the page source is different. By using ssr all the content injected into the page source that is why ssr is good for SEO and get better readability in search engines.

Meta tags

Meta tags play an essential part in search engine optimization. This tags usually defines your html page, what kind of content is there.

Lets see which meta tags we need to use for better visibility on search engines

<title> Page Title </title>

Defines your page title and it shows in the search result card as the title

- <meta name="description" content="Page description"/>

Defines your page description and it also show in the search result card as description

- <meta name="keywords" content="keyword1, keyword2" />

Keywords play a very import role in a webpage to come into search results. The keyword you give here the search engine will filter out them with the keywords and pick the most relevant. Using long keywords improves the chances to come into the search result.

e.g. how to use aws, how to use this software etc.

<meta property="og:title" content="Page title" />

- <meta property="og:description" content="Page description" />

- <meta property="og:image" content="Image url" />

All the above tags are used to show the content of your website when the url getting shared to any other platform like whatsapp, linkedin etc.

How to add the meta tags in NextJs?

NextJs supports dynamic metadata genaration based api response we can change the meta data. To do this just create function with the exact name  generateMetadata, and dont forget to export it. This function will automatically do everything for you.

1   export async function generateMetadata(){

2   const response = await fetch(url)

3   const data = await response.json();

4  

5   return {

6   title: data.title,

7   description: data.description,

8   keywords: [keyword1, keyword2],

9   openGraph: {

10   title: data.title,

11   description: data.description,

12   images: [data.image],

13   },

14   alternates: {

15   canonical: 'https://www.example.com',

16   }

17   }

18   }

Sitemap.xml

This files help search engines to know how many page are there in your website.

NextJs provides a way to generate the sitemap.xml dynamically. Just create file sitemap.js and export it inside src > app 

1   //sitemap.js

2  

3   export default function sitemap() {

4   return [

5   {

6   url: 'https://www.example.com',

7   lastModified: new Date(),

8   changeFrequency: 'yearly',

9   priority: 1,

10   },

11   {

12   url: 'https://www.example.com/about',

13   lastModified: new Date(),

14   changeFrequency: 'monthly',

15   priority: 0.8,

16   },

17   {

18   url: 'https://www.example.com/blog',

19   lastModified: new Date(),

20   changeFrequency: 'weekly',

21   priority: 0.5,

22   },

23   ]

24   }

this will generate a sitemap.xml file and it can be accesible at https://www.example.com/sitemap.xml

Robots.txt

This file enables your website to be crawled by the search engine crawlers. With this file we can configure which paths need to crawl and which not to.

Just create a file inside public folder with the exact name robots.txt

1   User-Agent: * //it means all the crawlers can crawl your website, you can also add specific crawler as well

2   Allow: /

3   Disallow: /private/ //disable paths you dont want to crawl

4  

5   Sitemap: https://www.example.com/sitemap.xml //sitemap url comes here

6  

Schema markup (ld+json)

Schema markup is a form of microdata that you can add to your website to improve how search engines interpret and display your content in search results.

Breadcrumb
Breadcrumb

Breadcrumb

This mircodata can be used in many parts in the search engines the screenshot shows on of the usecase.

How to add Schema Markup on Nextjs?

To add schema markup we have insert a script tag which content type should be ld+json and we place our json data just like the below format.

1   <script type="application/ld+json">

2   {

3   "@context": "https://schema.org",

4   "@type": "BreadcrumbList",

5   "itemListElement": [

6   {

7   "@type": "ListItem",

8   "position": 1,

9   "name": "Home",

10   "item": "https://www.example.com"

11   },

12   {

13   "@type": "ListItem",

14   "position": 2,

15   "name": "Blog",

16   "item": "https://www.example.com/blog"

17   },

18   {

19   "@type": "ListItem",

20   "position": 3,

21   "name": "Latest Blog Post Title",

22   "item": "https://www.example.com/blog/latest-blog-post-title"

23   }

24   ]

25   }

26   </script>

27  

1   //page.js

2  

3   const generateJsonLd = () => {

4  

5   const data = [

6   { label: 'Home', url: 'https://www.example.com' },

7   { label: 'About', url: 'https://wwww.example.com/about' },

8   { label: 'Portfolio', url: 'https://www.example.com/portfolio' },

9   { label: 'Blogs', url: 'https://www.example.com/blogs' },

10   { label: 'Services', url: 'www.example.com/services' }

11   ]

12  

13   const breadcrumbs = [];

14  

15   for (let index = 0; index < data.length; index++) {

16   const item = data[index];

17   breadcrumbs.push({

18   '@type': 'ListItem',

19   position: index + 1,

20   name: item.label,

21   item: item.url

22   })

23   }

24  

25   return {

26   "@context": "https://schema.org",

27   "@type": "BreadcrumbList",

28   "itemListElement": breadcrumbs

29   }

30   }

31  

32   const home = async () => {

33  

34   const jsonld = generateJsonLd();

35  

36   return (

37   <div>

38   <script

39   type="application/ld+json"

40   dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}

41   />

42   </div>

43   )

44   }

45  

To know more about schema markup check here

Caching

Caching is a technique where we store the highly processed data in a temporary storage and when we need it we directly take the data from cache instead of doing the heavy processs again. This helps our web page to load faster while we cache the data we get by a api call.  

To cache the api call data in NextJs we just need to export a variable call revalidate and we can provide a interval to revalidate the data after that time.

1   // page.jsx

2  

3   const fetchData = async () => {

4   const response = await fetch(url);

5   const json = await response.json();

6   return json;

7   }

8  

9   export const revalidate = 3600 // revalidate at most every hour

10  

11   const page = async () => {

12   const data = await fetchData();

13  

14   return (

15   <div>

16   {data.map((item) => (<p> {item.title} </p>))}

17   </div>

18   )

19   }

20  

21   export default page;

Image Optimization

Image optimization a essential aspect in search engine optimization. We need to use all the images properly otherwise it will not only decrease the website performance it will also impact page load speed and seo. 

The aspects we need keep in mind while optimizing images

  • Use the right file format (JPEG, PNG, WEBP)
  • Use properly sized images (give proper height and width)
  • Use Content Delivery Network (Cloudfront, Cloudinary)

To properly optimize image in NextJs use next Image component

1   import Image from 'next/image'

2  

3   export default function Page() {

4   return (

5   <Image

6   src={cdn url}

7   width={500}

8   height={500}

9   alt="Picture of the author"

10   />

11   )

12   }

Thank you for joining me in the journey of Search Engine Optimization for Next.js. I hope these tips and techniques help you enhance your website's visibility and performance on Google. Feel free to share your SEO successes and challenges in the comments below. Happy optimizing!

* * *