how to create a middleware in typescript

index.ts
// Define a middleware function signature
type Middleware = (req: any, res: any, next: () => void) => void;

// Create a middleware function
const myMiddleware: Middleware = (req, res, next) => {
    // Middleware logic
    console.log('Middleware executed');
    next(); // Call next to proceed to the next middleware or route handler
}

// To use the middleware in an Express application
// Example:
import express from 'express';

const app = express();

// Register the middleware using `app.use`
app.use(myMiddleware);

// Define a route handler
app.get('/', (req, res) => {
    res.send('Hello World');
});

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
748 chars
30 lines

In the code snippet above, we first define a type Middleware which represents a middleware function. Then, we create a middleware function myMiddleware which logs a message and calls next() to proceed to the next middleware or route handler.

To use this middleware in an Express application, we can register it using app.use(myMiddleware) and it will be executed for all incoming requests.

related categories

gistlibby LogSnag