Trim() in request body

Hello, does anyone know a global way where whenever you do a post or put or patch, you run the trim() in each field?

I use global middleware

class TrimString {
  async handle ({ request }, next) {
    const request_body = Object.keys(request.body)

    if (request_body.length) {
      request.body = Object.assign( => ({
          [key]: request.body[key].trim()

    await next()

module.exports = TrimString

Register in start/kernel.js

const globalMiddleware = [

Thanks a lot, it was a big help.

I made a small change to my code, in fact I got the second version of it and added only the IF to check for content, without the need to create a variable.

   if (Object.keys(request.body).length) {
      request.body = Object.assign(
        ...Object.keys(request.body).map(key => ({
          [key]: request.body[key].trim()

Awesome! Glad I could help.

1 Like

how to avoid null or empty values in this case, because it will throw exception for keys with null value.

Hello, as this project was just for studies what I did was convert to string before running the trim, as in the example of the link below:

Iā€™m sure this is not the best way but solved the first moment.