Everything you should know to improve SEO in your Next.js app

Everything you should know to improve SEO in your Next.js app

Essential Strategies and Tips for Boosting SEO Performance in Your Next.js Application

Introduction

To excel in SEO with Next.js, it is crucial to lay a strong foundation by focusing on fundamental aspects. Merely obtaining backlinks from reputable sources like The New York Times won't suffice if the basics are not effectively implemented.

At the core of successful SEO lies the principle of providing genuine value and utility to website visitors.

H1, H2, H3, p, div tags

H1, H2, H3

In most cases, a web page should utilize only these three heading tags: H1, H2, and H3. The hierarchy of H tags should be organized from H1 to H6, with H1 representing the most important heading and H6 the least important.

In most cases, there should be just one <h1> tag, and visually, it should be the biggest on the screen.

Good Example:

<h1>Best anime T-Shirts for 2023</h1>
    <h2>Naruto anime T-Shirts</h2>
        <h3>Naruto</h3>
        <h3>Sasuke</h3>
        <h3>Sakura</h3>
    <h2>Aot anime T-Shirts</h2>
        <h3>Levi Ackerman</h3>
    <h2>Dragon Ball anime T-Shirts</h2>
        <h3>Goku</h3>
        <h3>Vegeta</h3>

Bad Example (Incorrect H1 Placement):

<h2>Best anime T-Shirts for 2023</h2>
    <h1>Naruto anime T-Shirts</h1>
        <h3>Naruto</h3>
        <h3>Sasuke</h3>
        <h3>Sakura</h3>
    <h2>Aot anime T-Shirts</h2>
        <h3>Levi Ackerman</h3>

Bad Example (Incorrect Hierarchy):

<h1>Best anime T-Shirts for 2023</h1>
    <h3>Naruto anime T-Shirts</h3>
        <h4>Naruto</h4>
        <h4>Sasuke</h4>
        <h4>Sakura</h4>
    <h3>Aot anime T-Shirts</h3>
        <h4>Levi Ackerman</h4>

Bad Example (Incorrect Font Size):

<h1 className="text-sm">Best anime T-Shirts for 2023</h1>
    <h2 className="text-xl">Naruto anime T-Shirts</h2>
        <h3>Naruto</h3>
        <h3>Sasuke</h3>
        <h3>Sakura</h3>
    <h2>Aot anime T-Shirts</h2>
        <h3>Levi Ackerman</h3>

Avoid Styling Font Size with H Tags:

Another common mistake is styling your font size using <h> tags. Avoid doing this, and refrain from assigning <h> tags to everything.

p tag

Use <p> when you have a paragraph of text that represents a distinct block of content. A paragraph typically contains coherent information that is related to a specific topic or idea.

div

Use <div> when you want to group elements together for styling or layout purposes, and there is no semantic relationship between the content. A <div> is a generic container and doesn't provide any specific meaning to its content.

Conclusion

Remember to observe how major websites, like Amazon, structure their content by inspecting their elements. This will give you insights into how to properly use different HTML tags. For most regular text, use the <p> tag or place the content inside <div> containers. These practices will contribute to a well-organized and search engine-friendly web page built with Next.js.

Meta title

The meta title is a critical element for SEO and should be optimized for each page on your website. Let's take an example from an e-commerce website called "Roomy" that sells anime and manga clothing:

Example

<title>
Anime t-shirts and clothes, prices for 2023 – Roomy.rs
</title>

Keywords

To improve search engine visibility and accurately reflect your page's content, it's essential to include relevant keywords in your meta title. This can be achieved through thorough research using a variety of available tools like SEMrush, Ahrefs, and Google Search Console. Responsibility of keyword research lies with you, so make sure to do your homework diligently to identify the most suitable keywords for your content.

Max width of Meta Title on Google

The ideal meta title length is around 60 characters, not exceeding 600 pixels. However, keep in mind that character width can vary (e.g., "I" vs. "W"). To gauge how your title will appear on Google, it's best to use tools like the Moz tool to preview its appearance.

if you are brand

For branding purposes, consider adding your brand name at the end of the meta title. This format can look like: " - YourBrandName". Including your brand name helps reinforce brand recognition and association.

Year

Adding the current year (in this case, 2023) to the meta title is a good practice. It can catch the reader's attention and convey that your website is regularly updated, potentially increasing its credibility.

Additional advice

In your meta title and description, strive to intrigue your visitors and potential customers, but ensure that you deliver what you promise. Misleading visitors with deceptive titles or descriptions is detrimental to SEO. If users arrive at your website expecting one thing but find something else, they are likely to leave quickly, signaling to Google that your site is not helpful. This can lead to search engine ranking penalties. Always prioritize providing relevant and valuable content that aligns with your meta title and description. Crafting effective meta titles and descriptions that accurately represent your content and entice users can significantly impact your SEO performance and user engagement.

Meta Description

The meta description is a crucial element to entice users and provide a concise overview of the page content. Here's an example of a meta description for an e-commerce website offering anime and manga clothing:

Example

  <meta
    name="description"
    content="100% money back if you don't like the shirt for any reason! Free and fast shipping! Find a unique t-shirt with your favorite anime or manga hero.✅"
   />

Keywords

While keywords inside the meta description aren't as critical as they used to be, it's still a good practice to include relevant terms that align with the page's content. However, focus more on crafting a compelling and engaging description for users.

Max width of Meta Description on Google

The width of the meta description displayed on Google's search results page is an essential consideration. On desktop, the width is around 920px, allowing for approximately 150-160 characters. On mobile phones, the width is around 680px, allowing for around 120 characters. Make the most of this limited space by using engaging and concise language to attract users and improve click-through rates. Utilizing the maximum allowed length can also help build authority and interest among visitors.

Additional advice

To capitalize on psychological tactics, consider implementing this in your meta description. For instance, if you are not a massive corporate entity that requires a strict professional image, consider adding a checkmark (✅) at the end of your meta description. Placing it at the end is essential, as Google may not always display it correctly if it's in the middle. This subtle tactic can create a positive impression and encourage users to click on your link.

Remember, crafting an appealing meta description that aligns with your content and engages users can significantly impact click-through rates and the overall success of your page on search engine results pages (SERPs).

SSR

SSR (Server Side Rendering) is essential for optimizing your website's SEO. The reason behind this is that when using client-side rendering, crawlers can become confused because initially, there is no client-side rendered HTML available for them to analyze. However, with SSR, the page doesn't load until all HTML is fetched, providing a more complete picture for crawlers. Let me illustrate this with an example using console.log:

Example of SSR

export default function Home({ products }) {
  console.log(products);
  return (
    <div>
    </div>
  );
}

export async function getServerSideProps() {
  await db.connectDb();
  let products = await Product.find()
    .select("name subProducts slug subCategories")
  return {
    props: {
      products: JSON.parse(JSON.stringify(products)),
    },
  };
}

In this SSR example, when I console.log(products), upon refreshing the page, the data is immediately available.

Example of client-side

Now, let's look at an example of client-side fetching (with Axios):

import axios from "axios";
import { useEffect, useState } from "react";

export default function Home() {
  const [products, setProducts] = useState([]);

  const fetchData = async () => {
    try {
      const {data} = await axios.get(`/api/products`);
      setProducts(data.products);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };
  useEffect(() => {
    fetchData();
  }, []);
  console.log(products);
  return <div></div>;
}

In the client-side fetching example using Axios and useEffect, the data is fetched after the page has mounted. This delayed fetching can cause issues with search engine crawlers, as they may not be able to access and crawl the data properly. As a result, when you first log the data, you may encounter an empty array.

Lighthouse test

Performance is a critical aspect of SEO. If a user has to wait for more than a couple of seconds (or sometimes even just a second), they will likely leave your website immediately. As we discussed earlier, this is one of the worst outcomes you could face.

To assess and optimize your website's performance, I recommend installing the Lighthouse extension. When conducting the Lighthouse test, make sure to open it in incognito mode to eliminate any potential influence from caching, cookies, or other factors that could skew the results. To open a new incognito window, simply press "Ctrl + Shift + N" (in Chrome) or "Ctrl + Shift + P" (in Firefox) on your keyboard.

  1. Go to the webpage that you want to test in your incognito window.

  2. Open your web browser and go into incognito or private browsing mode. You can do this by pressing "Ctrl + Shift + N" in Chrome or "Ctrl + Shift + P" in Firefox.

  3. Right-click anywhere on the webpage and select "Inspect" or "Inspect Element" from the context menu. Alternatively, you can use the keyboard shortcut "Ctrl + Shift + I" in Chrome or "Ctrl + Shift + C" in Firefox.

  4. In the Developer Tools panel, click on the "More tabs" icon (three vertical dots or three horizontal lines, depending on your browser).

  5. Then, select "Lighthouse" from the available options.

  6. Once you click on "Lighthouse," a new window will open, prompting you to "Analyze page load". Click on it to start the Lighthouse test.

  7. Lighthouse is just warming up and doesn't want to start the test. Now, when I tried to click on "Analyze page load," I encountered an error. It happens sometimes. I haven't found a better solution than to restart my computer. It might happen to you as well, so don't worry. Just restart your computer and try to start the Lighthouse test again.

  8. When the test is successfully finished. Lighthouse will perform an audit of your webpage's performance, accessibility, best practices, and more. After completion, you'll see a detailed report with opportunities and diagnostics for improvement.

  9. Go through the Lighthouse report step by step, starting with the "Performance" section, and address any issues it highlights. Pay special attention to opportunities to optimize the page loading speed and resolve any diagnostic items related to accessibility, SEO, and best practices.

In most cases the performance is poor due to under-optimized images, I will give you further advice on this topic later in this blog, but i have another blog post that goes into detail on how to use <Image/> component in Next.js. By following these steps and implementing the recommended improvements from the Lighthouse report, you can enhance your website's performance, user experience, and overall SEO. Regularly monitoring and optimizing your website's performance is essential to ensure its success and user satisfaction.

In the world of SEO, link juice represents the valuable authority or ranking power passed from one webpage to another through hyperlinks. To grasp this concept better, envision your home page as having 100 points of link juice. EVERY SINGLE link on your home page, including those leading to social media platforms or external websites, contributes to distributing this link juice.

As a website owner, it's crucial to be mindful of the pages you choose to share link juice with. Strategic allocation can greatly influence your website's visibility and ranking potential. Additionally, it's advisable to minimize the number of links in the footer and eliminate any unnecessary ones. For instance, if you have both a "Contact" page and a "Location" page, consider consolidating them into a single page.

However, if certain URLs, such as "product 5" in our case in example, hold paramount importance, don't hesitate to link to them from the homepage, even repeating the link twice if necessary.

Example

  • HP (Home Page)

  • C (Contact Page)

  • PR (Products)

  • PP (Privacy Policy)

  • FAQ (Frequently Asked Questions)

  • P1, P2, P3, P4, P5 (Individual Product Pages)

Next.js <Image/> Component

In every project, I make it a point to ensure that I haven't accidentally used the standard <img/> tag for displaying images. Instead, I use the <Image/> component provided by Next.js. Most of you are likely familiar with this practice, but for those who aren't, I have a comprehensive blog post that explains how to use the <Image/> component in the best industry practices. However, I want to address one critical aspect that some of you might not be aware of, and that I didn't know at first either.

The Image component doesn't really cover the resizing

While the <Image/> component is fantastic for optimizing image loading and performance, it's important to note that it doesn't handle image resizing for you. For instance, if you have an image that's originally 1200 x 600 px, but you only need to display it as 600 x 300 px in your app, the <Image/> component won't automatically crop or resize the image accordingly. It's crucial to crop the image to the required dimensions using software like Canva, Photoshop or Cloudinary before implementing it with the <Image/> component. Try downloading the same image in both 1200 x 600 px and 600 x 300 px sizes, and you'll notice that the 600 x 300 px appears smaller even when used with the <Image/> component.

Images alt attribute

Before deploying my app into full production, I always make sure to perform a crucial step: searching for images without the alt attribute by typing alt="" in the search bar. When any image lacks this attribute, I immediately provide it with relevant information. For example, on individual product pages featuring product images, I assign the alt attribute a dynamic value like product.title.

         <Image 
            priority
            src={product.image_url}
            alt={product.title}
            width={500}
            height={750}
          />

Despite its significance for SEO, many people overlook the alt attribute and leave it empty, assuming it's irrelevant. However, this attribute plays a vital role in search engine optimization, as it allows screen readers to describe the images to visually impaired users and provides search engines with valuable information about the image content. Ensuring that all images have appropriate alt attributes can positively impact the accessibility and visibility of your website or application.

Next.js <Link/> component

I want to emphasize the importance of using the <Link/> component in Next.js for internal linking within your project. If you have mistakenly used the standard <a/> tag for internal links, I recommend searching for such instances in Visual Studio Code and replacing them with the <Link/> component. However, do keep in mind that for external URLs, like Instagram or Facebook accounts, you should continue using the <a/> tag.

Now, let me share an exciting feature of the <Link/> component that I recently discovered. When your link is in the viewport, the <Link/> component works behind the scenes to prepare that page for quicker loading. This prefetching capability significantly enhances user experience by reducing the perceived load time when they eventually click on the link. Prefetch can be disabled by prefetch={false}. It is only enabled in production.

Lang

Inside the _document.js file of your Next.js project, you can set the lang attribute of the Html tag to indicate the language of your website. For example, if your website is in Serbian, you would set the lang attribute to "sr":

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
//
    <Html lang="sr">
//
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

Similarly, if you are from Serbia but your website targets an English-speaking audience or is primarily in English, you would keep the lang attribute as "en".

Setting the correct lang attribute is essential for informing search engines and users about the primary language of your website, which can impact SEO and accessibility. Make sure to choose the appropriate language code that corresponds to your website's content and target audience.

Favicon

The favicon plays a significant role in people's psychology, as it can enhance their trust when they see the icon in Google search results. If, for some reason, your favicon doesn't appear on Google, don't worry, in most cases, you just need to be patient and wait for Google to process it properly.

However, if you encounter issues where the favicon doesn't show even on localhost, here's a simple solution to resolve it. Follow these steps:

  1. Create a new folder named "images" inside the "public" folder of your project.

  2. Place your favicon file inside the newly created "images" folder.

Next, open the _document.js file, and within the <Head> tag, add the following code:

<Head>
    <link rel="shortcut icon" href="/images/your-favicon.ico" />
</Head>

Replace "your-favicon.ico" with the actual filename of your favicon file.

URL

URLs should be kept short and concise to enhance user experience and ease of sharing.

URL extension

Regarding URL extensions, such as .com, .ai, or .org, they don't directly impact SEO performance in the eyes of search engines like Google. However, it's essential to consider that visitors do care about the URL extension. If your website has a relevant and recognizable domain extension, it can increase trust and credibility among your audience. When visitors have a positive experience, it can indirectly influence your website's SEO, as satisfied users are more likely to engage, share, and return to your site, leading to potential improvements in search rankings over time.

Meta SEO Inspector

Meta SEO inspector is a helpful tool for assessing your meta performance. By using this tool, you can gain valuable insights and receive guidance on potential areas of improvement. However, it's essential to note that the tool may not always be entirely accurate.

For instance, it might indicate that your <h1> tag is too long, but in reality, <h1> tags can be as lengthy as needed. Therefore, while the tool offers valuable assistance, it's crucial to exercise your judgment and knowledge to make informed decisions about your meta elements.

In summary, Meta SEO Inspector can be a useful companion in optimizing your website's meta aspects, but remember to consider its suggestions critically, keeping in mind the specific context and requirements of your content.

Canonical tag

what is a Canonical tag?

The Canonical tag, also known as the "rel=canonical" tag, is an HTML element used in web development and search engine optimization (SEO) to address issues related to duplicate content on websites. It is primarily used to tell search engines which version of a web page is the preferred or original version when there are multiple copies of the same content available under different URLs.

Duplicate content can occur on websites for various reasons, such as having different URL parameters, pagination, sorting options, or multiple versions of the same page for different devices (e.g., desktop and mobile versions).

By implementing the Canonical tag, website owners can specify the canonical (preferred) version of a page, indicating to search engines that this is the version they should consider for indexing and ranking.

Example where you should implement canonical tag

Let's consider an example where implementing the canonical tag becomes important. Suppose I'm working on an e-commerce project that sells t-shirts with various styles and sizes, but they all represent the same t-shirt design. To ensure proper indexing by search engines, I would include a canonical tag inside the head component, like this:

<Head>
    <link rel="canonical" 
        href={`/product/${product?.slug}?style=0`} 
        key="canonical"
     />
</Head>

By doing so, search engines, such as Google, will prioritize indexing this specific URL as the primary one, even if other URLs with different styles exist for the same t-shirt design.

How does Google pick the canonical URL?

Site's preferences

  1. Based on what did you specify with the canonical tag

  2. Redirects (redirect to the preferred URL, for example, if someone types "yourwebsite.com" but your preferred URL is "yourwebsite.com," you should redirect them to "yourwebsite.com" with a status code 307. In Vercel, this redirection is automatically done. Just choose the recommended options that Vercel suggests when picking your domain, and you will not have the problem).

  3. URL in the sitemap file: Google considers the canonical URL specified in the website's sitemap file. A sitemap is a vital file that lists all the pages on your website, aiding Google's search engine in effectively crawling and indexing the content. If you are unfamiliar with sitemaps or require guidance on their implementation, you can refer to another blog article on the topic.

  4. Preference for HTTPS URLs over HTTP: Google gives preference to HTTPS URLs over their HTTP counterparts for indexing. Since HTTPS offers improved security, it is often considered a positive ranking factor for enhancing search engine optimization (SEO).

  5. "Nicer" looking URLs: Google may favor shorter, more user-friendly URLs. Such URLs are visually appealing, easier for users to remember, and encourage better sharing experiences.

User's preferences

  1. which URL would be more useful for the user

If Google occasionally selects different URLs over time, it will not have a negative impact on the site. it simply reflects your preferences.

While backlinks are not specifically connected to programming, they hold immense importance. It's essential to keep this in mind. Having a good number of backlinks won't guarantee a spot on Google's first page if your website lacks strong fundamentals, especially for competitive keywords. The authority of the website providing the link matters significantly to Google, as it prioritizes secure and reliable information for its users. If a website with high authority links to your site, it signals trustworthiness to Google, leading to potential rewards.

If you want to learn effective strategies for building backlinks, I highly recommend following Adam Enfroy. He offers valuable insights on this topic, and I haven't come across a better resource.