Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express js enforcing request body types

is it possible to declare the types for the request body? I want to return bad request if the body contains other properties than the declared ones

import express from 'express'

const app = express()

app.use(express.json())

interface CustomRequest extends express.Request{
    body:{
        name:string
    }
}

app.post('/t', (req: CustomRequest, res: express.Response) => {
    res.send("hello world")
})

app.listen(5000, () => {
    console.log("app listening on 5000")
})
like image 977
Magna Avatar asked Mar 21 '26 10:03

Magna


1 Answers

I suggest you to take a look at @hapi/joi package web site. https://hapi.dev/module/joi/

It's easy to use and very powerful!

You can implement a middleware to validate the request (body, params, query) and also response objects! You can do it using the express-joi-validator package.

First you must import the modules:

const Joi = require('@hapi/joi');
const joiValidator = require('express-joi-validation')
  .createValidator();

Then define your schema (expected object structure)

const loginSchema = Joi.object({
    user: Joi.string().required(),
    password: Joi.string().required(),
});

Finally implement your middleware:

app.post('/login', joiValidator.body(loginSchema), (req, res) => {
    // Your logic here...
    res.send({status: 'ok'}); // Just an example
});

If validation fails it will send back to client a 400 (Bad Request) response!

Let me know if you have any question about it!

Hope it helps!

like image 157
lmoglia Avatar answered Mar 24 '26 00:03

lmoglia