Next Js SEO Complete Guide
How to handle SEO in Next.js Application: The Developers Handbook is a guide for Next.js developers to learn how to optimize their applications for search engines. The guide covers a wide range of topics, including:
- Understanding SEO fundamentals: What is SEO? Why is it important? How do search engines work?
- Optimizing Next.js metadata: How to use Next.js's built-in Metadata API to define and manage SEO metadata for your application.
- Generating dynamic SEO metadata: How to generate SEO metadata for dynamic pages and content.
- Improving page performance: How to make your Next.js pages load quickly and efficiently, which is important for both SEO and user experience.
- Using structured data: How to use JSON-LD to markup your content with structured data, which can help search engines better understand and rank your pages.
- Testing and monitoring your SEO: How to use SEO tools to test and monitor your application's SEO performance.
SEO fundamentals
What is SEO?
Search engine optimization (SEO) is the process of optimizing a website or web page so that it ranks higher in search engine results pages (SERPs) for relevant keywords. When a user searches for a keyword, search engines like Google and Bing return a list of websites that are relevant to that keyword. The higher a website ranks in the SERPs, the more likely it is that users will click on it.
Why is SEO important?
SEO is important because it can help you attract more visitors to your website. When your website ranks higher in SERPs, more people will see it and click on it. This can lead to increased traffic, leads, and sales.
How do search engines work?
Search engines use a variety of factors to rank websites, including:
- Keyword relevance: Search engines try to match the keywords that users are searching for with the content of websites.
- Page authority: Search engines give more weight to websites that have high authority. Authority is determined by factors such as the number of backlinks a website has, the quality of those backlinks, and the age of the website.
- Page quality: Search engines also consider the quality of the content on a website. This includes factors such as the readability of the content, the use of images and videos, and the overall user experience.
Understanding SEO fundamentals is essential for any Next.js developer who wants to optimize their applications for search engines. By understanding the basics of how search engines work and what factors they consider when ranking websites, you can make informed decisions about how to improve your application's SEO performance.
Here are some additional notes on SEO fundamentals:
- Keyword research: The first step to optimizing your website for SEO is to conduct keyword research. This involves identifying the keywords that your target audience is searching for and that are relevant to your website.
- On-page optimization: Once you have identified your target keywords, you need to optimize your website's content and structure for those keywords. This includes using the keywords throughout your website, including in your page titles, meta descriptions, headers, and body text.
- Off-page optimization: Off-page optimization involves building backlinks to your website from other high-quality websites. Backlinks are one of the most important factors that search engines use to determine the authority of a website.
By following these SEO fundamentals, you can improve your Next.js application's visibility in search engine results pages and attract more visitors to your website.
Adding favicon to your application
Favicon
- Head to https://favicon.io/ (opens in a new tab) and upload your logo png and then genrate the favicon
- Add a
favicon.ico
image file to the root/app
route segment.
Layout Metadata (Global SEO set up)
To define static metadata, export a Metadata
object (opens in a new tab) from a layout.js
or static page.js
file.
These metatags can help search engines better understand your website and rank it higher in search results pages. They can also help social media platforms display your website content more prominently. The metadata object you have provided contains the following metatags:
- MetadataBase: This metatag tells search engines and social media platforms where to find the root of your website.
- Title: This metatag is the most important metatag for SEO. It tells search engines what your website is about and what pages on your website are relevant to specific search queries.
- Description: This metatag provides a brief overview of your website and its content. It is often used by search engines to display a snippet of text on search results pages.
- ApplicationName: This metatag is not as important for SEO as the other metatags, but it can be useful for social media platforms to identify your website.
- Keywords: This metatag is a list of words and phrases that are relevant to your website content. It can help search engines better understand your website and rank it higher for relevant search queries.
- Authors: This metatag identifies the authors of your website content. It can be helpful for social media platforms and other websites to display your content more prominently.
- Creator: This metatag identifies the creator of your website. It is not as important for SEO as the other metatags, but it can be helpful for other websites to identify your website and link to it.
- Publisher: This metatag identifies the publisher of your website. It is not as important for SEO as the other metatags, but it can be helpful for other websites to identify your website and link to it.
- Alternates: This metatag specifies alternate URLs for your website in different languages. This can be helpful for search engines and social media platforms to display your website content to users who are searching in different languages.
- openGraph: This metatag specifies metadata for social media platforms, such as Facebook and Twitter. This metadata can be used to display your website content more prominently on social media.
- twitter: This metatag specifies metadata for Twitter. This metadata can be used to display your website content more prominently on Twitter.
Create a Site config file
Create a folder called config
and in it create site.ts
Add the following Code in the site.ts file. Fill in all the necessary informaton
export const siteConfig = {
name: "Online Docs ",
title: "Its the best on the Market ",
url: "https://ui.shadcn.com",
ogImage: "https://ui.shadcn.com/og.jpg",
description:
"Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.",
links: {
twitter: "https://twitter.com/shadcn",
github: "https://github.com/shadcn-ui/ui",
},
};
export type SiteConfig = typeof siteConfig;
Update the Global Layout file with metadata informaton
import type { Metadata } from "next";
import { siteConfig } from "@/config/site";
export const metadata: Metadata = {
title: {
default: siteConfig.title,
template: `%s - ${siteConfig.title}`,
},
metadataBase: new URL(siteConfig.url),
description: siteConfig.description,
keywords: [
"buy online",
"best deals",
"discount shopping",
"online marketplace",
"shop now",
"free shipping",
"exclusive offers",
"trendy products",
"customer favorites",
"latest arrivals",
],
authors: [
{
name: "stockify",
url: "https://stockify.com",
},
],
alternates: {
canonical: "/",
languages: {
"en-US": "/en-US",
},
},
creator: "stockify",
openGraph: {
type: "website",
locale: "en_US",
url: siteConfig.url,
title: siteConfig.name,
description: siteConfig.description,
siteName: siteConfig.name,
images: [
{
url: siteConfig.ogImage,
width: 1200,
height: 630,
alt: siteConfig.name,
},
],
},
twitter: {
card: "summary_large_image",
title: siteConfig.name,
description: siteConfig.description,
images: [siteConfig.ogImage],
creator: "@shadcn",
},
icons: {
icon: "/favicon.ico",
shortcut: "/favicon-16x16.png",
apple: "/apple-touch-icon.png",
},
manifest: `${siteConfig.url}/site.webmanifest`,
};
Metadata for individual Pages (Server and Client Side)
- For the Normal Pages, such as about, blogs just add the following code.
If a page has a layout file, the put the code in the layout file
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Beautiful Charts",
description:
"Built using Recharts. Copy and paste into your apps. Open Source.",
};
Extended Metadata from Layout to Single Pages
Dynamic Pages SEO - Generate metadata
If in your app you have some bit of data fetching from a server or db, then you can generate the metadata dynamically. You can use generateMetadata
function to fetch metadata that requires dynamic values.
Fetch the Metadata dynamically as shown below.
//app/products/[slug]
export async function generateMetadata({ params: { slug } }) {
//Fetch all the products, then find a single product
const products = await getProducts();
const product = products.find((product) => product.slug == slug);
return {
title: product?.title,
description: product?.seoDescription,
alternates: {
canonical: `/products/${product?.slug}`,
},
openGraph: {
title: product.title,
description: product.description,
images: [product.thumbnail],
},
};
}
Generating Static Params
The generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.
export async function generateStaticParams() {
const posts = await fetch("https://.../posts").then((res) => res.json());
return posts.map((post) => ({
slug: post.slug,
}));
}
OpenGraph-image and twitter-image
The opengraph-image
and twitter-image
file conventions allow you to set Open Graph and Twitter images for a route segment.
- They are useful for setting the images that appear on social networks and messaging apps when a user shares a link to your site.
- The recommended Image Size is
1200 x 630px
- Use an image file to set a route segment's shared image by placing an opengraph-image or twitter-image image file in the segment.
- You can set different images for different page groups but for simplicity add your images to
/app
directory to set them to be used throught out the entire site - To create these images you can use canva.com (opens in a new tab) or any other photo editing software
- Inother words create 4 files og imageConfigDefault, twitter image , og alt text and twitter image alt text and place them in the app directory
They are useful for setting the images that appear on social networks and messaging apps when a user shares a link to your site.
opengraph-image
(opens in a new tab)
Add an opengraph-image.(jpg|jpeg|png|gif)
image file to any route segment.
twitter-image
(opens in a new tab)
Add a twitter-image.(jpg|jpeg|png|gif)
image file to any route segment.
opengraph-image.alt.txt
(opens in a new tab)
Add an accompanying opengraph-image.alt.txt
file in the same route segment as the opengraph-image.(jpg|jpeg|png|gif)
image it's alt text.
twitter-image.alt.txt
(opens in a new tab)
Add an accompanying twitter-image.alt.txt
file in the same route segment as the twitter-image.(jpg|jpeg|png|gif)
image it's alt text.
Check your social media share previews
You can check your social previews using online tools and here are some
-
For apps on Localhost you can use docs.srv.us (opens in a new tab) to generate a link you can use online temperalliy or Just use an extension likeSeo meta in 1 click (opens in a new tab)
Other SEO Quick Tips
-
Use Next/Font - Make sure in your layout your usung font loaded from "next/font" avoid using the google font links used in css. This will ensure that the loaded and hosted locally on our website
-
Use Next Image - Using Next Image Optimises all your images, such as loading different Image Variations for different Screen sizes
-
Use Next Link - To Cache all the Pages
Sitemap
A sitemap is a file that lists all of the pages on your website, along with their corresponding URLs and other relevant information. Sitemaps are used by search engines to crawl and index your website more efficiently.
Sitemaps are useful for SEO in a number of ways:
- They help search engines discover all of the pages on your website.This is important because search engines need to be able to index all of your pages in order to rank them in search results pages.
- They provide search engines with information about the structure of your website.This information can help search engines to understand the relationships between your pages and to rank them more accurately.
- They can help search engines to prioritize crawling and indexing your most important pages. This can help your most important pages to rank higher in search results pages.
Generate Static Sitemap
Add a sitemap.js
or sitemap.ts
file that returns Sitemap.
//app/sitemap.ts
export default function sitemap() {
return [
{
url: "https://acme.com",
lastModified: new Date(),
changeFrequency: "yearly",
priority: 1,
},
{
url: "https://acme.com/about",
lastModified: new Date(),
changeFrequency: "monthly",
priority: 0.8,
},
{
url: "https://acme.com/blog",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.5,
},
];
}
Generate Dynamic Sitemap
If your fetching data in your application, then you need to generate your sitemap dynamically. so modify your sitemap.js
//app/sitemap.js
import getCategories from "./libs/getCategories";
import getProducts from "./libs/getProducts";
export default async function sitemap() {
const baseUrl = "https://lighthousefurniture.com";
const products = await getProducts();
const categories = await getCategories();
const productUrls = products.map((product) => {
return {
url: `${baseUrl}/products/${product.slug}`,
lastModified: new Date(),
};
});
const categoryUrls = categories.map((category) => {
return {
url: `${baseUrl}/categories/${category.slug}`,
lastModified: new Date(),
};
});
return [
{
url: baseUrl,
lastModified: new Date(),
},
{
url: `${baseUrl}/about`,
lastModified: new Date(),
},
{
url: `${baseUrl}/contact`,
lastModified: new Date(),
},
...productUrls,
...categoryUrls,
];
}
Generate Static Robots.txt
A robots.txt file is a text file that tells search engine crawlers which pages on your website they are allowed to crawl and index. Robots.txt files are important for SEO because they can help you to control how your website is indexed and ranked by search engines.
Here are some of the benefits of using a robots.txt file:
- You can prevent search engines from crawling and indexing pages that are not ready for public viewing.This can be useful for pages that are still under construction or that contain sensitive information.
- A robots.txt file can be used to give search engines the exact location of your sitemap. This can help search engines to find your sitemap more easily and to crawl and index your website more efficiently.
export default function robots() {
const baseUrl = "https://lighthousefurniture.com";
return {
rules: {
userAgent: "*",
allow: ["/", "/product", "/category"],
disallow: [],
},
sitemap: `${baseUrl}/sitemap.xml`,
};
}
Google My Business
- Google My Business helps your Business rank Locally and here is a full Guide from Mailchimp, that i found usefull 👉 here (opens in a new tab)
How to set up your account
If you’ve already got a Google My Business account set up, skip ahead to the optimization section. If you haven’t, here’s how to claim your location in Google business listing. Please note that Google occasionally makes updates, so some of the wording may be a little different. Just follow these easy steps:
- Go to google.com/business (opens in a new tab).
- Click “Manage now.”
- Enter your business name and click “Next.”
- Enter your address. If you’re a service area business and don’t have a physical store but deliver services (such as a plumber or electrician), click the “I deliver goods and services to my customers” and “Hide my address” checkboxes.
- Choose your primary business category. It’s important to pick the most accurate category that describes what you do.
- Add your phone number.
- Add your website URL
Google Search Console
- Google Search Console (GSC) is a free tool that helps you monitor your site’s search performance and technical SEO healthand here is a full Guide from Semrush, that i found usefull 👉 here (opens in a new tab)