Docs
Middleware
Middleware
The zely is based on the osik aimed at light weight and speed. Reading the osik documentation will help you understand.
#Middleware Usage
Middleware in Zely is a function that has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Here's an example of a middleware function:
middlewares/message.ts
import { Middleware } from 'zely';
export const Message: Middleware = (ctx, next) => {
(ctx as any).message = 'Hello World!';
next();
};
pages/index.ts
export default [
GET((ctx) => {
ctx.send(ctx.message);
}),
];
This middleware function, named Message, adds a property message to the request object and assigns it the value 'Hello World!'. The next() function call is used to pass control to the next middleware function.
#Middleware Registration
To use the middleware, you need to add it to the config.middlewares array in your Zely configuration file:
zely.config.ts
import { Message } from './middlewares/message';
export default defineConfig({
middlewares: [Message],
// ...
});
#Page Middleware
You can create middleware that only works on a specific page.
ERROR
next()
cannot be used in this page middlewareTypescript
import { middleware } from 'zely';
export default [
middleware((ctx) => {
ctx.num = 10;
}),
GET((ctx) => {
return { number: ctx.num };
}),
];
#Auto Mode
See next page.