Skip to main content

Custom Middleware

Godspeed provides usage of application level middleware functions. You can add any custom middleware functions which will have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

14.1 How to add custom middleware in Godspeed

Step 1: Create an index.js/index.ts file in src/middlewares dierctory in your project.

Project structure
├── config
└── src
└── middlewares
└── index.ts

Step 2: index.ts/index.js should be exporting array of middleware functions with signature (req, res, next)

import { uuid } from 'uuidv4';

function addUuid(req: any, res: any, next: any) {
// Set data
req.body.uuid = uuid();

// Go to next middleware

function addTitle(req: any, res: any, next: any) {
// Set data
req.body.title = "Title from middleware/ts";

// Go to next middleware

export default [addUuid, addTitle];

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Sample req object
Here, two properties uuid and title are added in the body of req object.

"_events": {},
"_eventsCount": 1,
"httpVersionMajor": 1,
"httpVersionMinor": 1,
"httpVersion": "1.1",
"complete": true,
"rawHeaders": [
"gzip, deflate, br",
"rawTrailers": [],
"aborted": false,
"upgrade": false,
"url": "/test3",
"method": "POST",
"statusCode": null,
"statusMessage": null,
"_consuming": true,
"_dumped": false,
"baseUrl": "",
"originalUrl": "/test3",
"params": {},
"query": {},
"body": {
"uuid": "cfc5fc7f-cfdf-4fe7-99ad-08993f90f570",
"title": "Title from middleware/ts"
"_body": true,
"id": 2,
"log": {},
"route": {
"path": "/test3",
"stack": [
"name": "<anonymous>",
"keys": [],
"regexp": {
"fast_star": false,
"fast_slash": false
"method": "post"
"name": "<anonymous>",
"keys": [],
"regexp": {
"fast_star": false,
"fast_slash": false
"method": "post"
"methods": {
"post": true
"protocol": "http",
"secure": false,
"ip": "::ffff:",
"ips": [],
"subdomains": [],
"path": "/test3",
"hostname": "localhost",
"host": "localhost",
"fresh": false,
"stale": true,
"xhr": false,
"files": []