Embracing Jamstack for Better Web Performance: A Fullstack Developer's Guide to Next.js and Vercel

As a web developer, you know that user experience is key when it comes to creating successful web applications. Users expect fast page load times, seamless navigation, and intuitive interfaces. However, achieving these goals can be a challenge when using traditional server-based environments.

This is where Jamstack architecture comes in. Jamstack stands for JavaScript, APIs, and Markup. This modern architecture model promotes building fast, secure, and scalable web applications by decoupling the frontend from the backend. With Jamstack, websites are built using only static assets like HTML, CSS, and JavaScript, which can be stored on a content delivery network (CDN) for faster global distribution.

In this article, we'll explore how Jamstack architecture can improve your web performance and overall user experience. We'll also learn how to build, deploy and manage your fullstack web applications using Next.js and Vercel.

Why Jamstack architecture?

Jamstack architecture provides multiple benefits over traditional server-based environments, which can help build web applications that load faster and with fewer hassles. Let's see some of them:

Better Performance

With Jamstack, your web application is pre-rendered and served as static HTML, which ensures fast page load times. Additionally, resources like images, videos, and stylesheets are optimized and served from a global content delivery network (CDN), further reducing load times and increasing performance.

Because Jamstack only uses APIs for dynamic functionality, the server is never overloaded with too many requests at once. Instead, APIs like Netlify or Vercel provide an optimized API for handling necessary requests, like form submissions or user authentication.

Scalability

Since Jamstack follows the "static-first" paradigm, it's inherently scalable. Even if your web application experiences a sudden spike in traffic, the CDN will continue to serve content as usual, as it is capable of handling millions of requests.

This means that Jamstack architecture can save you from the hassle and costs associated with scaling traditional server-based environments.

Security

With Jamstack, your website is exposed to fewer attack vectors, as it is only served as static files on a CDN with no server-side APIs. Additionally, since many features are carried out through APIs, updates and features can be pushed out securely since the frontend is already built and doesn't need to be altered.

Why Next.js?

Next.js is a React framework that allows the developer to build server-side rendered (SSR) or statically generated (SSG) sites, easily adding dynamic functionality on top of static pages.

Some of the features that make Next.js a great choice for Jamstack web development include:

  • Automatic Bundling: Next.js automatically optimizes and bundles your code, ensuring you always serve your users optimized and readable code.
  • Automatic Code-splitting: Next.js automatically splits your code into smaller chunks, helping your application load faster.
  • Incremental Static Regeneration: Next.js allows developers to update static pages without regenerating the entire page. This feature makes content updates faster since the server only updates what needs to be updated.

Why Vercel?

Vercel is a cloud platform for deploying Jamstack applications with ease. It offers an all-in-one solution for continuous deployment, asset optimization, and serverless functions.

Some of the features that make Vercel a great choice for Jamstack hosting and development include:

  • Continuous Deployment: With Vercel, you can automatically deploy your website to production via GitHub, GitLab, BitBucket, or any other Git provider. Vercel will take care of everything, from building your site to deploying it to the CDN.
  • Asset Optimization: Vercel automatically optimizes your assets like images, videos, and stylesheets, helping your site load faster and increasing web performance.
  • Serverless Functions: Vercel allows you to easily add serverless functions to your application, enabling you to perform complex tasks without the need for an entire server.

Building a Fullstack Jamstack Application with Next.js and Vercel

Now that we know the benefits of Jamstack architecture and the advantages of using Next.js and Vercel, let's build a fullstack Jamstack application.

Prerequisites

In this tutorial, we'll use the following stack:

  • React
  • Next.js
  • Vercel
  • Netlify Functions

Make sure you have Node.js installed and an up-to-date version of NPM or Yarn. We'll also assume you've installed Git.

Getting Started With Next.js

First, let's scaffold a new Next.js project.

Open your terminal, navigate to your project directory, and run the following commands:

$ npx create-next-app my-app
$ cd my-app
$ npm run dev

After running these commands, your app should be running at http://localhost:3000. You should see a welcome page.

We're now ready to build our fullstack Jamstack application!

Creating Our API with Netlify Functions

The first step in building our application is to create an API that will handle user registration and login. For this, we'll use Netlify Functions, which is a serverless backend offering from the popular hosting service Netlify.

Create a new folder called api at your project root. Inside this folder, create a new file called signup.js.

$ mkdir api
$ cd api
$ touch signup.js

Open the signup.js file in your editor and copy the following code:

export default (req, res) => {
  const { username, password } = req.body;

  // Perform validation, hashing, etc.

  res.status(200).json({ success: true });
}

This code exports a function that handles an HTTP request made to our API. We expect this request to contain a JSON object with a username and password field.

In a real application, you would need to perform validation to ensure that the user submitted valid information, and then probably store the user's information in a database, such as MongoDB or Firebase.

For now, we won't handle any database, so we'll just send back a JSON object with a success field set to true.

We now need to deploy our API. For this, we'll use Netlify.

Deploying Our API to Netlify Functions

Before we deploy our API to Netlify, we need to connect our Next.js app to our API.

Create a new file called netlify.toml in your project root:

$ touch netlify.toml

Add the following configuration to this file:

[build]
  functions = "api/"

[dev]
  functions = "api/"

This tells Netlify to look for functions in our api/ folder.

Open the .env.local file in your project and add the following variables:

NETLIFY_SITE_ID=my-netlify-site-id
NETLIFY_FUNCTIONS_BASE=my-functions-base-url

Replace the value of NETLIFY_SITE_ID with your real Netlify site ID. You can find your site ID in the "Site Details" section of your Netlify dashboard.

Replace the value of NETLIFY_FUNCTIONS_BASE with the base URL of your Netlify functions. This should be something like https://my-netlify-site-id.netlify.app/.netlify/functions/.

In the signup.js file, add the following code to the top:

const siteId = process.env.NETLIFY_SITE_ID;
const functionsBase = process.env.NETLIFY_FUNCTIONS_BASE;

This code retrieves the values of the NETLIFY_SITE_ID and NETLIFY_FUNCTIONS_BASE environment variables we just set.

Now, open the index.js file in your project and add the following code:

import fetch from 'isomorphic-unfetch';

export default function Home() {
  const register = async () => {
    const res = await fetch('/.netlify/functions/signup', {
      method: 'POST',
      body: JSON.stringify({
        username: 'test',
        password: '1234'
      })
    });
    console.log(await res.json());
  };

  return (
    <div>
      <button onClick={register}>Register</button>
    </div>
  );
}

Here, we're importing the fetch function from the isomorphic-unfetch library, which allows us to make HTTP requests from both the client and server.

In the Home component, we're defining a function called register(). This function makes an HTTP request to our API to register a new user. The request contains a JSON object with a username and password field.

The register() function is called when the "Register" button is clicked. After the request is made, we log the response to the console.

We're now ready to deploy our project to Vercel.

Deploying Our Project to Vercel

To deploy our Next.js project to Vercel, we need to link our GitHub repository to Vercel and set up our build configuration.

  1. Sign in to your Vercel account and navigate to the dashboard.
  2. Click "Import Project" and select your GitHub repository.
  3. Select "Next.js" as the framework preset.
  4. In the bottom left corner of the page, click "Advanced Settings".
  5. In the "Build & Development Settings" section, add the following environment variables:
NETLIFY_SITE_ID = your-netlify-site-id
NETLIFY_FUNCTIONS_BASE = your-netlify-functions-base-url

Replace the values with your real Netlify site ID and functions base URL, respectively.

Now click "Deploy" to deploy your project to production.

After a few minutes, your project will be live at a URL that looks something like this: https://my-next-js-app.vercel.app/.

And that's it! You've successfully built and deployed a fullstack Jamstack application using Next.js and Vercel.

Conclusion

Jamstack architecture is a powerful way to build fast, secure, and scalable web applications. By combining Next.js and Vercel, we can take full advantage of Jamstack architecture to create web applications that load quickly and provide an overall better user experience.

Whether you're building a simple blog or a complex web application, Jamstack architecture can help you create a better web experience for your users.