Handling Middleware in Next.js

Marickian
By -
0
Handling Middleware in Next.js - A Tutorial

Handling Middleware in Next.js - A Tutorial

At the conclusion of this tutorial, we'll briefly delve into the concept of middleware in Next.js.

Middleware is essentially a mechanism to execute operations before a request is fully processed. In our case, we'll keep it simple to cover the basics, as our upcoming project will utilize an authentication service called Clark for handling intricate details.

Let's start by creating a special file with either a .js or .ts extension in the root directory. This file must be named middleware.

To create the middleware file:

new file: middleware.js

Within this file, we export a function with the same name. For now, let's focus on logging information.

export default function middleware() {
    console.log('Hello World');
}

Restart the server to ensure changes take effect:

npm run dev

This middleware function will be invoked for every route by default. Now, let's navigate to the browser to see the console logs.

Next, let's explore controlling which routes are affected by the middleware. We can achieve this by setting up a configuration.

export const config = {
    matcher: '/about',
};

Now, if we visit the /about route in the browser, the middleware will be triggered, and a JSON response will be sent back with the message "hello there".

Additionally, we can restrict access to specific resources using middleware. By utilizing the next response, we can redirect users as needed. For instance, if a user attempts to access certain routes like /about or /tasks, they will be redirected to the home page.

Post a Comment

0Comments

Post a Comment (0)