You need to enable JavaScript to run this app.
NextSaaS Logo
NextSaaS Logo
Published on

Maximize website performance with Next.js and NextSaaS

Explore NextSaaS.live to learn about the strategies we've used to enhance performance, accessibility, and SEO.

Posted by:
xjasonsong

xjasonsong

Founder of NextSaaS

When searching for performance improvements, you'll find an overwhelming amount of information online. The possibilities for enhancing performance, accessibility, best practices, and SEO seem endless.

Fortunately, many modern frameworks like Next.js offer numerous built-in benefits. With the NextSaaS boilerplate, you can easily achieve impressive performance scores for all your websites. Let's take a closer look at NextSaaS.live to see what steps we've taken to achieve these performance results.

Static vs Dynamic Rendering

What is Static Rendering?

Static rendering involves fetching and rendering data on the server at build time (when you deploy) or during data revalidation. Whenever a user visits your application, the cached result is served. Here are some benefits of static rendering:

  • Faster Websites: Prerendered content can be cached and globally distributed, ensuring users around the world can access your website's content more quickly and reliably.
  • Reduced Server Load: Because the content is cached, your server doesn't have to dynamically generate content for each user request.
  • SEO: Prerendered content is easier for search engine crawlers to index since the content is already available when the page loads. This can lead to improved search engine rankings.

Static rendering is useful for UIs with no data or data shared across users, such as static blog posts or product pages. It might not be suitable for dashboards with personalized data that are regularly updated.

What is Dynamic Rendering?

Dynamic rendering involves rendering content on the server for each user at request time (when the user visits the page). Here are some benefits of dynamic rendering:

  • Real-Time Data: Dynamic rendering allows your application to display real-time or frequently updated data, making it ideal for applications where data changes often.
  • User-Specific Content: Serving personalized content, such as dashboards or user profiles, and updating data based on user interaction is easier with dynamic rendering.
  • Request Time Information: Dynamic rendering enables you to access information only known at request time, such as cookies or URL search parameters.

NextSaaS leverages static rendering to optimize performance and user experience. All stateless pages, such as documentation, CMS-generated pages, and even the homepage, are generated statically at build time.

You might wonder how we achieve dynamic behavior, like the group button on the header displaying differently, on these static pages. The answer lies in using client components.

Static pages are generated without rendering the client components. These client components are rendered when the static page loads in the browser. This approach allows us to mix static and dynamic content, ensuring a fast, reliable, and interactive user experience.

Semantic HTML and ARIA Roles

Semantic HTML and ARIA (Accessible Rich Internet Applications) are essential for enhancing the accessibility of digital products, particularly for individuals using assistive technology (AT) such as screen readers.

Using semantic HTML elements like <header>, <nav>, <main>, and <footer> helps convey the structure and meaning of web content to both browsers and assistive technologies. This approach improves navigation and understanding for users relying on screen readers.

ARIA roles, properties, and states complement semantic HTML by providing additional information about elements that may not be conveyed through HTML alone. For instance, adding aria-label attributes to buttons, inputs, and other interactive elements helps ensure that users with visual impairments can understand their purpose.

Here's a straightforward implementation:

<div aria-label="Copy the Canonical link"></div>

SEO

SEO (Search Engine Optimization) is crucial for ranking your website higher on Google and driving more traffic. The SEO strategy used in NextSaaS can be outlined in three parts:

Meta Tags for Pages -

Meta tags provide essential information about your website to search engines and social media platforms, improving your site's visibility and click-through rates. NextSaaS dynamically creates meta tags to ensure each page is optimized.

Here's how NextSaaS dynamically creates meta tags:

export const metadata: Metadata = {
  title: {
    default: SITE.title,
    template: `%s | ${SITE.name}`,
  },
  keywords: SITE.keywords,
  authors: [
    {
      name: SITE.creator,
      url: SITE.name,
    },
  ],
  creator: SITE.creator,
  description: SITE.description,
  metadataBase: new URL(SITE.url),
  openGraph: {
    type: "website",
    locale: "en_US",
    url: SITE.url,
    title: SITE.title,
    description: SITE.description,
    siteName: SITE.name,
    images: [
      {
        url: ogUrl(SITE.title),
        width: 700,
        height: 577,
        alt: SITE.name,
      },
    ],
  },
  twitter: {
    card: "summary_large_image",
    title: SITE.title,
    description: SITE.description,
    images: [
      {
        url: ogUrl(SITE.title),
        width: 700,
        height: 577,
        alt: SITE.name,
      },
    ],
    creator: SITE.creator,
  },
  robots: {
    index: true,
    follow: true,
    "max-image-preview": "large",
    "max-snippet": -1,
    "max-video-preview": -1,
    googleBot: "index, follow",
  },
  alternates: {
    canonical: SITE.url,
  },
  applicationName: SITE.name,
  appleWebApp: {
    title: SITE.title,
    statusBarStyle: "default",
    capable: true,
  },
  manifest: `${SITE.url}/site.webmanifest`,
  icons: {
    icon: [
      {
        url: "/favicon.ico",
        type: "image/x-icon",
      },
      {
        url: "/favicon-16x16.png",
        sizes: "16x16",
        type: "image/png",
      },
      {
        url: "/favicon-32x32.png",
        sizes: "32x32",
        type: "image/png",
      },
      {
        url: "/android-chrome-192x192.png",
        sizes: "192x192",
        type: "image/png",
      },
      {
        url: "/android-chrome-256x256.png",
        sizes: "192x192",
        type: "image/png",
      },
      {
        url: "/apple-touch-icon.png",
        sizes: "180x180",
        rel: "apple-touch-icon",
      },
      {
        url: "/safari-pinned-tab.svg",
        color: "#5bbad5",
        rel: "mask-icon",
      },
    ],
    shortcut: [
      {
        url: "/favicon.ico",
        type: "image/x-icon",
      },
    ],
  },
  other: {
    "msapplication-TileColor": "#da532c",
  },
};

Automatic Sitemap Generation -

Sitemaps are essential for SEO as they help search engines crawl and index your website more effectively. NextSaaS utilizes automatic sitemap generation to ensure that search engines have up-to-date information about all the pages on your site.

Powered by next-sitemap, NextSaaS employs the next-sitemap package to automatically generate sitemaps on the server side. This tool simplifies the process of creating and updating sitemaps, ensuring that search engines always have the latest information about your website's structure.

Key Features

Automatic Indexing: The next-sitemap package generates an index sitemap that includes all your site's pages.

Dynamic Routes: As new pages or posts are added to NextSaaS, the routes are automatically included in the sitemap, keeping it up-to-date without manual intervention.

import { ROUTES } from "@/config/site";
import { ENV } from "@/env.mjs";
import { getPublishedDocumentSlugs } from "@/lib/cms";
import { getServerSideSitemap } from "next-sitemap";
 
export async function GET() {
  // Method to source urls from cms
  const result: any = [];
 
  Object.keys(ROUTES).forEach((key) => {
    if (
      (ROUTES as any)[key].path != "/" &&
      !(ROUTES as any)[key].excludeFromSEO
    ) {
      result.push({
        loc: ENV.NEXT_PUBLIC_APP_URL + ((ROUTES as any)[key].path as string),
        lastmod: new Date().toISOString(),
        changefreq: "daily",
        priority: 0.7,
      });
    }
  });
 
  (await getPublishedDocumentSlugs("pages")).forEach((slug) => {
    result.push({
      loc: ENV.NEXT_PUBLIC_APP_URL + ROUTES.pages.path + "/" + slug,
      lastmod: new Date().toISOString(),
      changefreq: "daily",
      priority: 0.8,
    });
  });
 
  (await getPublishedDocumentSlugs("posts")).forEach((slug) => {
    result.push({
      loc: ENV.NEXT_PUBLIC_APP_URL + ROUTES.posts.path + "/" + slug,
      lastmod: new Date().toISOString(),
      changefreq: "daily",
      priority: 1,
    });
  });
  return getServerSideSitemap(result);
}

Script Optimization -

Next.js offers a built-in <Script> component to manage and optimize the inclusion of external scripts on your website. This component provides enhanced control over how and when scripts are loaded, which can help improve page performance and user experience.

Using the <Script> Component

The <Script> component allows you to add and configure external scripts with fine-grained control over their loading behavior. For example, you can use it to integrate Google Analytics into your Next.js application.

<Script
            id="gtag-init"
            async
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
              __html: `
                    window.dataLayer = window.dataLayer || [];
                    function gtag(){dataLayer.push(arguments);}
                    gtag('js', new Date());
                    gtag('config', '${gtag.GA_TRACKING_ID}', {
                        page_path: window.location.pathname,
                    });
                    gtag('config', '${gtag.AD_TRACKING_ID}');
 
                    if (window.location.pathname.includes('${ROUTES.checkoutSuccess.path}')) {
                      gtag('event', 'conversion', {'send_to': '${gtag.AD_TRACKING_ID}/1v-xxx'})
                    }
                    `,
            }}
          />

To wrap up, here is the build output for further insights into the optimizations and performance enhancements. Thank you for reading, and happy exploring!