Is middleware considered server or client-side in Next.js 13?
Asked Answered
P

1

7

I'm currently working on a Next.js 13 project and I'm trying to understand the role of middleware within the framework. In Next.js 13, is middleware considered server-side or client-side?

I have looked at the Next.js documentation where i can't find an explanation whether middleware is client side or server side.

Could someone clarify whether middleware in Next.js 13 is categorized as server-side or client-side? Additionally, it would be helpful to understand any specific use cases or limitations for middleware in this version of Next.js.

Pontus answered 5/7, 2023 at 12:52 Comment(2)
It's server side of course (just because to do anything with the response you need to import import { NextResponse } from 'next/server'). As for use cases, it's too broad question, it basically allows you to do anything with the response. From the docs: you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.Roath
There are a number of places in Next where the conventions of "servers" get blenderized with the conventions of "clients", because the whole brand of Next is SSR and combining those two. This does not, however, mean that everywhere you see a traditionally "server-side" syntax convention is inherently a server-only functionality. In this case, it would be more precise to say that 'request' and 'response' are conventions for the general concept of route-handlers, and client-side applications certainly have those, and a 'router'.Practical
Q
0

It can be used on the client side.

I personally prefer to use route authentication, because it checks the token before the page rerenders.

Note: If you use the React's context and try to access a protected route, you first load the page and then the context is set, so you go outside the application (you can make it work better but basically it's the behavior).

The downside is that you have to be aware that there is a middleware in your application and you need to set it to pages/routes that you want to access.

For more information, I found this article that I found clarifying.

Quintie answered 19/10, 2023 at 11:9 Comment(2)
middleware written in middleware.ts file at root level is server side only. Event if you write "use client" at the top, it will still be server side only.Hellhound
From official docs: "The middleware.js|ts file is used to write Middleware and run code on the server before a request is completed."Cushion

© 2022 - 2024 — McMap. All rights reserved.