githubEdit

Middlewares

Middleware is a function which is called before the actual request handler.

Middleware functions have access to the request and response contextarrow-up-right, and the next() middleware function is in the application’s request-response cycle. The next() middleware function is commonly denoted by a variable named next. Every request made by the client has to pass through a middleware function, where this request can be validated, modified, and/or extended. An Epic API middleware, by default, is equivalent to Oakarrow-up-right middleware.

You can execute the following command to create a middleware:

# Execute the built-in Deno task
deno task create:module -t middleware -n checkAuth --template blank.ts

This command is going to generate the following code:

middlewares/checkAuth.ts
import { type RouterContext } from "oak";

// If this is a global middleware, do not add arguments to the factory function.
export default () =>
  async (ctx: RouterContext<string>, next: () => Promise<unknown>) => {
    // Your logic here...

    // Continue to the next middleware
    await next();
  };

By default, Epic API registers middleware on a global level. If you want to add this middleware to a specific controller or a route, then you can add this middleware to the excludes array in the middlewares/.sequence.json file. Your file should look similar to the following:

middlewares/.sequence.json
{
  "sequence": ["checkAuth.ts"],
  "excludes": ["checkAuth.ts"]
}

Your middleware checkAuth.ts will be removed from the global scope. Now you can import this middleware into any controller. See the following example:

If you want to add this middleware to a specific route, See the following example:

Use the following command to delete the middleware:

circle-exclamation

Last updated