![]() |
VOOZH | about |
Edge Functions are serverless functions that run close to the user, reducing latency and improving performance. They handle dynamic content, API requests, and personalization efficiently.
If you've ever used serverless functions, the above definition may sound familiar.
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.
Step 1: Run the following command to create a new Next.js application:
npx create-next-app@latest myprojectThe 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.
Run the Application: Open the terminal and enter the following command.
npm run devOutput: