Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing Node apps.
Use JWT-Based, Stateless Authentication
We can authenticate by using JSON web tokens.
A JSON web token consists of 3 parts.
They include:
- header with the type of the token and hashing algorithm
- payload has the claims
- a signature that signs the payload.
We can add it easily with some add-ons.
For instance, we can use the koa-jwt package to add the token.
We can write:
const koa = require('koa')
const jwt = require('koa-jwt')
const app = koa()
app.use(jwt({
secret: 'secret'
}))
// Protected middleware
app.use(function *(){
this.body = {
foo: 'bar'
}
})
We just call app.use
to use the jwt
middleware.
The object has the secret to sign the token.
Then we added a protected middleware after that.
The token content will be available with this.state.user
.
The JWT module doesn’t depend on any database layer.
They’re all verified on their own.
They can also contain the time to live values.
To ensure that our communication is secure, we still have to ensure that API endpoints are available through an HTTPS connection.
Use Conditional Requests
Conditional requests are HTTP requests that have different results depending on the request header values.
The headers check whether a version of a resource stored on the server match a given version of the same resource.
The headers can be the timestamp since the last modification.
It can also be an entity tag, which differs for each version.
The headers are:
Last-Modified
which indicates when the resource was last modifiedEtag
which is the entity tagIf-Modified-Since
which is used with theLast-Modifed
headerIf-None-Match
used with theEtag
header.
Use Rate Limiting
We can limit the number of requests that can be made to our API.
To tell our API clients how many requests are left, we can set the following response headers:
X-Rate-Limit-Limit
, tells us the number of requests allows in a given time intervalX-Rate-Limit-Remaining
, the number of requests remaining in the same intervalX-Rate-Limit-Reset
, tells us the time when the rate limit will be reset
We can add libraries to add rate limit capabilities to our app.
With Koa, we can use the koa-ratelimit package.
Create a Proper API Documentation
It’s hard to know how to use our API without any documentation.
To make our lives easier, we can use API Blueprint or Swagger to create our documentation.
Future of APIs
There’re alternatives to REST.
We can use GraphQL to listen to HTTP requests, but it has type checking and we can selectively select resources.
With type checking and the ability to selectively query resources, we can be more efficient and reduce the chance of errors.
Conclusion
We can use JWT for authentication.
Conditional requests let us make requests differently according to headers.
Alternatives to REST APIs should also be considered.