Open In App

Edge Functions and Middleware in Next JS

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO.

Until recently, there were primarily two methods for serving content to the user’s browser:

  • Statically from a Content Delivery Network close to the user’s location for faster response time.
  • Dynamically with different content and logic on each request from a single server.
  • Both methods have limitations, such as the CDN’s inability to cache dynamic content and the server’s inability to match the CDN’s delivery speed.

What are Edge Functions?

Vercel introduced Edge functions to achieve CDN’s speed and server-side’s flexibility. Edge functions enable developers to run their code at the servers distributed globally. This means that your code will be executed in a more convenient location for your user. This allows developers to move server-side logic to the edge, closer to the origin of your visitor, for faster response time.

If you’ve ever used serverless functions, the above definition may sound familiar.

How Edge functions are different from serverless functions?

  • Low Latency: Our code deployed on the edge is replicated to many global locations, so it is executed from the user’s closest geographical location. Low latency will be experienced by users from all over the world.
  •  No Cold Boots: When a serverless function is called, it requires a cold start of about 250ms before execution, but edge functions provide 100x faster boot time and reduce start time to almost 0ms.

Working with Edge functions:

Before we begin, you should familiarize yourself with the term middleware. It’s not a new concept, but it was only recently introduced in Next JS. Middleware is a function that executes before every request made to Next.js. So, if a user requests a page, the logic of the middleware function is executed first, followed by the request. Middleware introduced by Vercel will execute on edge functions.

Steps to Create the React Application And Installing Module:

Step 1: Run the following command to create a new Next.js application:

npx create-next-app@latest myproject

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

  "dependencies": {
"next": "^7.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: To demonstrate edge functions in action, we’ll create a small application with Next.js. We’ll begin by creating a new Next.js project, then use Next.js middleware to implement protected routes. A secret key will be required to access protected routes; otherwise, the user will be redirected to the homepage.

Javascript




import React from 'react'
 
const Home = () => {
  return (
    <h1>Home Page</h1>
  )
}
 
export default Home


Javascript




/pages/protected.js
 
import React from 'react'
 
const Protected = () => {
  return (
    <div>Secret Data</div>
  )
}
 
export default Protected


Javascript




//pages/middleware.js
 
import { NextResponse } from "next/server";
 
// This function will act as middleware
const middlewareHandler = (req) => {
 
  // We'll first check if route includes
  // the protected path
  if (req.url.includes("/protected")) {
 
    // Get the secret from the url params
    const urlParams = new URLSearchParams(req.nextUrl.search);
    const secret = urlParams.get("secret");
 
    // Check if secret exists, if it does
    // then it must be correct.
    if (secret && secret === "mysecret") {
 
      // If secret matches we will continue
      // to the protected route.
      return NextResponse.next();
 
    } else {
 
      // If the secret doesn't exist or is incorrect
      // we'll redirect to the index (Home) page.
      return NextResponse.redirect("http://localhost:3000/");
    }
  }
 
  // For all other routes, we won't change anything.
  NextResponse.next();
   
};
export default middlewareHandler;


Run the Application: Open the terminal and enter the following command.

npm run dev

Output: 

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads