Middleware

Middlewares run on the server side.They allow you to intercept incoming requests before the route is handled.

Middleware is useful for tasks such as authentication, access control, request filtering, and other server-side checks.

Registering Middleware

Middlewares are registered in the nijor.config.js file.


        import auth from "@/middlewares/auth.js";
        // ...
        export const middlewares = [auth()];
        // ...
    

Nijor runs these middlewares on the server for incoming requests.

Middleware Structure

A middleware is usually written as a function that returns an async handler.The handler receives req, res, and next.


        function middleware(opts) {
            return async function(req, res, next) {
                // middleware logic
                next();
            }
        }
    

Call next() to pass control to the next middleware or continue request processing.

Use Cases

Middleware can be used to protect routes, validate requests, or intercept requests before they reach the page or endpoint.

A common use case is checking cookies to prevent unauthorized access to protected routes.


        function auth() {
            return async function(req, res, next) {
                const token = req.cookies?.token;

                if (!token) {
                    res.statusCode = 401;
                    res.end("Unauthorized");
                    return;
                }

                next();
            }
        }
    

Intercepting Requests

Since middleware runs before the request is completed, it can intercept requests and decide what should happen next.

A middleware may allow the request to continue, modify the response, or stop the request entirely.

Note

It is recommended to keep all your middlewares in separate files inside the src/middleares directory and import them in the nijor.config.js.