Creating Routes in KoaJS
Learn how to create dynamic routes using KoaJS Route Parameters.
Join the DZone community and get the full member experience.
Join For FreeKoaJS is a minimal and flexible NodeJS web application framework. It provides a good set of features for building web and mobile applications. In this post, we will be getting started with KoaJS by creating a small application.
KoaJS is an open-source framework. It is developed and maintained by the creators of the extremely popular ExpressJS.
However, the design philosophy behind KoaJS was completely different from Express. Koa provides a minimal interface to build applications. It is a very small framework, which provides the bare minimum tools to build apps and REST APIs
Routes are an important aspect to build any web application. However, KoaJS does not support routes as part of the core module. Therefore, we have to use an external module to enable routing. In this post, we will look at a basic Koa JS Router Example using the koa-router
package.
While static routes can solve a large number of use-cases, an application also needs dynamic routes. Dynamic routes help us pass parameters as part of the route path. In this post, we will also learn how to handle KoaJS Route Parameters with examples.
1 – Installation of KoaJS Packages
KoaJS requires Node version 7 or above. This enables it to work with ES2015 and async function support.
To get started with KoaJS, we can simply create a project folder and execute the below commands
$ mkdir koa-app
$ cd koa-app
$ npm init -y
$ npm install --save koa
Basically, we create a directory and initialize an npm project. Then, we use npm to install koa
.
Now that our project is ready, we can create our first KoaJS application.
See the below example:
const koa = require('koa');
const app = new koa();
app.use(async ctx => {
ctx.body = 'Hello, World';
});
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
A KoaJS application is an object containing an array of middleware functions. These middleware functions are composed and executed in a stack-like manner upon request.
As you can see, we have the app.use()
function. Basically, this function is a middleware. This function takes a callback function as input. Also, the callback function gets access to the Koa application context known as ctx
. Basically, we can use this context to access and modify the request and response objects.
Once we start the application using node index.js
and visit http://localhost:3000
, we will be able to see the greeting message in the browser.
However, Unlike ExpressJS, Koa does not come with in-built router handling capability.
Assuming that you already have a KoaJS application, we only need to install another package to work with routers.
$ npm install koa-router
Once the package installation is complete, we are ready to tweak our application to utilize the koa-router
package.
2 – Implement a KoaJS Router Example
Let us implement a simple GET route example
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const router = new Router();
router.get('/greetings', (ctx, next) => {
ctx.body = "Hello, World from Router"
});
app.use(router.routes())
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
Let us understand what is happening in the above example.
- We first import the necessary packages. This includes
koa
andkoa-router
. - Next, we create a Koa application instance using the constructor and
new
keyword. - Also, we create an instance of the
koa-router
. - Now, we can attach the route definitions to the router instance. For example, to attach a GET route, we call
router.get()
function. This function takes the route path as input and a callback function that contains the Koa application context. - Within the callback, we set the response body to the required greeting message.
- Moving on, we call
app.use()
to attach the route definitions to the KoaJS middleware stack. - Finally, we call
app.listen()
to start the application on port 3000.
Note here that the Koa Context is a special object that encapsulates the request
and response
objects of NodeJS into a single object. In KoaJS, a context instance is created per request and is referenced in the middleware as the receiver or the ctx
identifier.
If we start the application at this point and visit http://localhost:3000/greetings
, we will be able to see the greeting message in the browser.
3 – Handling KoaJS Route Parameters
Let us create a simple example demonstrating route parameters in KoaJS.
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const router = new Router();
router.get('/books/:id', (ctx, next) => {
ctx.body = 'Book requested for id: ' + ctx.params.id
});
app.use(router.routes())
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
As you can see, we added :id
in the path within the router.get()
function. The router function is part of the KoaJS Router package.
Basically, :id
is a placeholder for a route parameter. Once we define the route parameter, we can retrieve the value for the parameter from the ctx.params
object.
If we start the above application and visit http://localhost:3000/books/5
, we get the output message as ‘Book requested for id: 5’.
We can also send anything other types of value in the id
field (such as a string) and even that will be available in ctx.params
.
Lastly, it is also possible to have multiple route parameters in KoaJS.
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const router = new Router();
router.get('/books/:id', (ctx, next) => {
ctx.body = 'Book requested for id: ' + ctx.params.id
});
router.get('/books/:bookId/author/:authorId', (ctx, next) => {
ctx.body = {bookId: ctx.params.bookId, authorId: ctx.params.authorId}
});
app.use(router.routes())
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
For example, here the second route contains two parameters – bookId
and authorId
. We can retrieve both from the ctx.params
object.
4 – Pattern Matching With Route Parameters
We can also use regex to restrict URL parameter matching.
For example, if our requirement says that the bookId
should only be 3 digits long number, we can use regex as follows:
router.get('/books/:id([0-9]{3})', (ctx, next) => {
ctx.body = 'Book requested for id: ' + ctx.params.id
});
Note that this will only match if the id is 3 digits long. Anything less or more will result in an HTTP 404 error code. We can also build complex REST APIs in KoaJS using different HTTP methods.
Conclusion
With this, we have successfully looked at KoaJS Route Parameters and how to handle them in our application.
Basically, route parameters make our application routes dynamic and flexible. Also, we can use multiple parameters in the route and also perform pattern matching using regex.
If you have any comments or queries about this post, please feel free to mention them in the comments section below.
Published at DZone with permission of Saurabh Dashora. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments