Categories
Koa Nodejs

Validating Request Data with Koa

Spread the love

Koa is a small framework that lets us create backend apps that run on the Node.js platform.

In this article, we’ll look at how to validate request data type with Koa.

Validating Request Data Type Using the request.is Method

We can call the ctx.is method with the string for the data type that we’re checking for to check if the data type from the Content-Type header’s value matches what we have in the argument.

It can take one or more data types. For instance, we can use it as follows:

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  if (ctx.is('text/*', 'text/html')){
    ctx.body = 'valid';
  }
  else {
    ctx.body = 'invalid';
  }
});

app.listen(3000);

In the code above, we called the ctx.is method with the strings for 2 data types, which are ‘text/*’ and ‘text/html’ to check if the incoming request have any of these values as the value of its Content-Type header.

If one of these values are includes, then it returns 'valid' as the response body.

Otherwise, it returns 'invalid' .

Content Negotiation

Content Negotiation is a mechanism that’s used to serve different representations of a resource from the same URL. We can use the user agent that can specify which is best suited for the user.

When making requests to the client, we can use the Accept , Accept-Charset , Accept-Encoding , or Accept-Language headers in the request to let the server know what kind of data the client accepts.

With that data, the server can return a response with the most suitable kind of data for the client.

For instance, we can use it as follows:

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  if (ctx.accepts('html')){
    ctx.body = 'accepts html';
  }
  else if (ctx.accepts('application/json')){
    ctx.body = 'accepts json';
  }
  else if (ctx.accepts('image/png')){
    ctx.body = 'accepts png';
  }
  else {
    ctx.body = 'accepts everything';
  }
});

app.listen(3000);

In the code above, we called the ctx.accepts method with the content-type string that we want to check for in those headers listed above, so that we can return the appropriate response for it.

Then when we make a request to our app with one of those headers and application/json as its value, then we get the string 'accepts json' returned as the response.

Checking for the Encoding that the Client Accepts

We can use the ctx.acceptsEncodings method to check what kind of encoding the client accepts.

It takes one more encoding type strings as its argument or it can be one array of encoding type strings.

For instance, we can use it as follows:

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  if (ctx.acceptsEncodings('gzip') === "gzip"){
    ctx.body = 'accepts gzip';
  }
  else {
    ctx.body = 'does not accept gzip';
  }

});

app.listen(3000);

In the code above, we called the ctx.acceptEncodings method with the argument 'gzip' . The method returns the encoding that’s the best match.

Then if we make a request to our app with the Accept-Encoding header gzip, deflate, br , we’ll get that the response 'accepts gzip' from the app.

If no arguments are given, then all accepted encodings are returned.

Checking the Character Set That’s Accepted By the Client

We can call the acceptsCharsets to check for the character sets that are accepted by the client.

It also takes one or more string for the character set names that are accepted or an array of strings with those character set names.

For instance, we can use it as follows:

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {

  if (ctx.acceptsCharsets('utf-8') === 'utf-8'){
    ctx.body = 'accepts utf-8';
  }
  else {
    ctx.body = 'does not accept utf-8';
  }

});

app.listen(3000);

The code above is similar to the acceptEncodings code.

If we make a request that doesn’t include the Accept-Charset header that includes utf-8 , then we’ll get ‘does not accept utf-8’ returned as the response.

Otherwise, we’ll get 'accepts utf-8' returned whether we made the request explicitly with the Accept-Charset header with utf-8 as the value or not.

Checking the Language of the Request

The ctx.acceptsLanguages let us check the language of the request according to the Accept-Language header.

It’s similar to the other 2 methods above with the arguments that it takes and what it returns.

Get Any Header Field

We can get any request header field with the ctx.get method. For instance, we can write the following to do that:

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  ctx.body = ctx.get('foo');
});

app.listen(3000);

In the code above, we called the get method with the 'foo' header name. It returns the value of the 'foo' header if it exists.

Then when we make a request with the foo header with value bar , we’ll see 'bar' returned as the response.

Conclusion

We can use the ctx.is method to validate data types that are sent to the server.

To do content negotiation, we can use the accepts method. To check the language, encoding, or character set, there’re methods to do that.

Finally, we can get any request header value with the get method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *