next.js-tutorial

Next.js API MiddleWares

The API Middleware layer, in essence, serves the same purpose as middleware in other IT solutions. It lies between the client and the systems of record, converting the customer’s wishes into action in the fundamental systems of record.

Middleware is a piece of code that allows you to change the response to a request before it’s finished. Based on the user’s request, we can rewrite, redirect, add headers, or even stream HTML.

Getting Started with NextJS

Open up the directory you’d like to create your project in and run:

npm install next@latest

npx create-next-app api-middle-wares

After the installation is complete, you can navigate to your new project directory:

cd api-middle-wares

Once there, start your development server:

npm run dev

And once the server is ready, you can open up http://localhost:3000 in your browser where you can now see your new Next.js app!

A straightforward middleware

Now we need to create a _middleware.js file in our pages directory to add middleware. It’s worth noting that you can put middleware files in subdirectories of the pages directory to have them run after the top-level middleware file.

Now let us write a simple middleware function –

const middleware = (req, ev) => {
  return new Response(req.ua.os.name);
};

export default middleware;

This will display the user’s OS system on the website. Let’s explore how we may rewrite routes beneath the hood now that we’re streaming HTML to the user.

Under the hood, a middleware that rewrites the route

To begin, create a new file called [os].js and paste the index.js code into it, substituting the function name with the name of the function.

[os].js –

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by Vercel
            and Replit
        </a>
      </footer>
    </div>
  )
}

Now let us go back to our _middleware.js file and make some changes. First we will import NextResponse

import {NextResponse} from "next/server"

Now, let us store the user’s operating system in a variable

const os = req.ua.os.name

Now, we can rewrite the URL to the new route we created and that is where NextResponse comes in.

return NextResponse.rewrite(`/${os}`) // This return is necessary

This is how out _middleware.js files should look now –

import {NextResponse} from "next/server"

const middleware =  (req, ev) => {
  const os = req.ua.os.name

  return NextResponse.rewrite(`/${os}`)
};

export default middleware;

Now let us import Next Router in our new route

import {useRouter} from "next/router"

As this is a react hook, we need to create a new instance of the NextJS router inside of the function being returned.

const router = useRouter()

We can get the operating system of the user from the URL parameter we rewrote earlier in the middleware

const os = router.query.os

At last, let us show the user what operating system they are using

<h1 className={styles.title}>
      You are using the {os} operating system
</h1>

At last this is how are [os].js should look like –

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import {useRouter} from "next/router"

export default function Os() {
  const router = useRouter()

  const os = router.query.os
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          You are using the {os} operating system
        </h1>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by Vercel
            and Replit
        </a>
      </footer>
    </div>
  )
}

If we go to the home page now, we should see something like this (notice that part of the nextjs boilerplate code has been removed) –

Using the browser dev tools, I can simulate the browser user agent, and we receive a different answer for the operating system –

What is the inner workings of NextJS middleware?

Vercel’s Edge Functions, which run on the V8 Engine, are used by NextJS middleware. The V8 Engine is a Google-maintained Javascript engine written in C++. It’s far faster than using NodeJS in a virtual machine or container, and Vercel says that these edge functions are instantaneous.

Edge function limitations

Some NodeJS APIs, such as the filesystem API, are not available with middleware (since they are edge functions). Additionally, some NodeJS modules will not operate because only modules that implement ES Modules and do not use any native NodeJS APIs are permitted.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.