Server-Side Middleware

Middlewares run strictly on the server side. They intercept incoming HTTP requests before the request reaches the page routing logic or API endpoint.

Middleware is essential for handling global or route-specific operations, such as user authentication, access control lists (ACLs), request logging, request filtering, and CORS header management.

Registering Middleware

To activate middleware in a Nijor application, import your middleware handlers and register them inside the middlewares array within the nijor.config.js configuration file:


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

Nijor automatically executes registered middlewares sequentially for every incoming server request.

Middleware Structure

A Nijor middleware is typically structured as a factory function that returns an asynchronous handler. The returned handler receives three core arguments:

req: The native Node.js/Bun server request object.

res: The native Node.js/Bun server response object.

next: A callback function used to pass control flow to the next middleware in line.


        function customMiddleware(options) {
            return async function(req, res, next) {
                // Custom server-side processing goes here
                
                // Call next() to allow execution to proceed
                next();
            };
        }
    

You must call next() to pass control forward. If you do not call next(), the request will hang indefinitely unless you manually end the response via the res object.

Use Case: Route Authentication Guard

A common use case for server-side middleware is validating request tokens (e.g., from cookies or headers) to prevent unauthorized access to private pages.


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

                if (!token) {
                    res.statusCode = 401;
                    res.end("Unauthorized: Missing or invalid token");
                    return; // Prevent next() from executing
                }

                // If authorized, continue request execution
                next();
            };
        }
    

Request Interception & Termination

Because middleware executes before the page or api response begins compiling, it holds full authority over the request lifecycle. A middleware can decide to:

    Allow the request: Perform a check or enrich the request context, then trigger next().

    Redirect the request: Modify headers (such as "Location") and complete the response immediately.

    Terminate the request: Respond with an error code (e.g., '401 Unauthorized' or '403 Forbidden') and call res.end(), short-circuiting downstream operations.

Best Practices

To keep your project structure clean and manageable, we recommend keeping each middleware in its own file inside the dedicated src/middlewares directory, importing them into your central nijor.config.js only when needed.