Middleware System
What is middleware?
Let's examine the diagram below:

In the above flow, a request is triggered from the end-user. This request is received and processed by a series of middleware functions. After all middleware functions are executed, a response object containing the webpage data is sent to the client.
Middleware functions execute during the lifecycle of a request to the server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to. Middleware can be written to perform a variety of tasks. For example, a logging middleware might log all incoming requests to your application, or an authentication middleware might verify an incoming user's credentials.
Let's examine an example of a middleware function:
import { del } from "@evershop/postgres-query-builder";
import { pool } from "@evershop/evershop/lib/postgres";
export default async (request, response, next) => {
try {
const attributeIds = request.body.ids;
await del("attribute")
.where("attribute_id", "IN", attributeIds.split(","))
.execute(pool);
response.json({
data: {},
success: true,
});
} catch (e) {
response.json({
data: {},
message: e.message,
success: false,
});
}
};
EverShop Middleware Types
EverShop has four types of middleware functions:
1. Application-level Middleware
Application-level middleware functions are executed on all requests, including both admin and front store pages, even on 404 pages.
For example, a logging middleware that records information about all requests is an application-level middleware.
In a module, you can create an application-level middleware function by creating a file in the api/global or pages/global folder. For example, if you create a file named logMiddleware.ts in the api/global folder, this middleware will be executed on all API requests.
2. Admin-level Middleware
Admin-level middleware functions are executed on all requests to the admin panel.
For example, an authentication middleware that verifies admin credentials is an admin-level middleware.
In a module, you can create an admin-level middleware function by creating a file in the api/admin/all or pages/admin/all folder. For example, if you create a file named authMiddleware.ts in the pages/admin/all folder, this middleware will be executed on all pages in the admin panel.