title: Should I always compile Ajv schema in express?
body: <p>I want to use the <a href="https://ajv.js.org/" rel="nofollow noreferrer">Ajv validator</a> to validate the request bodies of my <code>express</code> app.</p>
  <p>To use the validator, we first need to compile the schema we want to test against, and then run the validation, like this:</p>
  <pre class="lang-js prettyprint-override"><code>const Ajv = require('Ajv');
  const ajv = new Ajv();
  
  const schema = {
    type: 'object',
    required: ['username', 'password'],
    properties: {
      username: {
        type: 'string',
        minLength: 3,
      },
      password: {
        type: 'string',
        minLength: 8,
      },
    },
  };
  
  /* What we want to validate */
  const body = {
    username: 'johndoe',
    password: 'secret'
  };
  
  /* We compile the validator */
  const validate = ajv.compile(schema.query)
  
  /* We test our data to see if it is valid */
  const valid = validate(body)
  </code></pre>
  <p>Should I always compile the validator when my endpoints are called, and so include it inside my routes, or can I leave the compile process outside the route body?</p>