FE Snack: Next.js Middleware is Exciting

Hey friend,

Last week, I announced that I'd been working on a FREE Email course and asked if you would like to be part of the React Server Components Course Test Squad.

The testing began today 🎉, and the course has been shipped 🚀. I'm very excited and wouldn't have done this without you all, so thank you 🙏.

It's still possible if you want to be a part of it. Click on this button 👇

I also asked you to let me know what topic you would like me to cover, and many of you mentioned: Next.js Middleware, so here you go.

Our Weekly Snack: Next.js Middleware

What is Next.js Middleware?

It's the middle person between your Frontend and your Backend.

Typically, When our Frontend makes an API call, it will go to the backend. But when a Middleware is involved, when our Frontend makes an API call, it will go to the Middleware first, and Middleware will decide if the request should be forwarded to Backend.

If a Backend API performs some code, such as checking if the user is valid. Instead of every API invoking the same code, you can ask Middleware to handle it.

User Logging In

An example of this is the user logging in. Once the users log in, we want only to allow users to access, let's say, our /dashboard route if their login credentials are valid. Of course, this means every backend API that the Frontend calls need some logic that checks for the user's validity.

This is a great use case for Middleware. We can move the code inside the Middleware.ts file. If the user has valid credentials, great, we can redirect them to /dashboard, but if not, redirect them back to login or not do anything at all.

Why request the Backend when we know it will be invalid? This might result in the Backend performing several unwanted operations or every backend API performing the same operations.

Example Operations a Middleware can perform.

A list of operations could be checking if the user is valid. If their login credentials are still valid, they should be redirected. All these questions can be handled in the Middleware.

Let's look at the Middleware code: Redirect Example,

Click on the image to copy the code

Because we create a new file in Next.js called middleware.ts in the src directory or the same level as the pages directory, our routes will go through middleware.ts.

The Frontend Developers Toolbox 🧰

👉 Tell me a bit more about you

Wow, so many new folks have joined, Welcome!! 👏

This newsletter has grown quite a bit since I started it a few months ago. I’d love to get to know you a bit better. Can you please click one of the links below to best describe your situation,

I hope you have a great day!

A Frontend Newsletter that you'll love! 💖