Create Node.JS APIs With Koa, Yarn Workspaces and Objection.js

Syed Riyaz Uddin
2 min readAug 15, 2022

It’s gonna be a small but beautiful journey

Courtesy: Rob Owen-Wahl at Pixabay

I am a full-stack developer who uses Laravel’s magic to unveil the best of the best for my clients in a dramatically small timeline. I do prefer using battery-included frameworks to save development time and ensure everything I do gets me more productive and gives me a lot of time to procrastinate.

But recently, I had to build things with Node JS because of my client’s scalability requirements. So, I thought why not write my journal while I code 🤔.

Now it’s time to select the frameworks, for which I had three requirements:

  1. The application must be as magical as Laravel
  2. The application must use MySQL
  3. Authentication must be as smooth as cheese(burger?)

I could’ve chosen the wonderful Adonis.js (Inspired by Laravel) but the client had another requirement: The app must be scaled and split into tiny Microservices. due to which, I had to go down the different path.

Talk is cheap, show me the code…

Alright, I chose the following specifications to make my job easier (Just like in laravel):

  1. Language: Node.JS (Of Course)
  2. Framework: Koa JS (Built on top of Express with some exceptional features)
  3. ORM: Objection.js (Chose after a few google searches, syntactical comparisons with sequelize, etc and reddit opinions)
  4. Database: MySQL

Let’s Get Started With The Installation

//Create a new folder and type the following:
yarn init
yarn add koa koa-router koa-jwt koa-body @koa/cors objection knex mysql mysql2yarn start

Not a good way of teaching, but had to do it quick (I’ll separate them later). here’s the brief about all the above things:

Koa: Async lightweight NodeJS Framework with better error handling

Koa-router: To handle routes (requests to the server)

Koa-JWT: To authenticate user using JSON Web Tokens

Koa-Body: To parse POST request body

@koa/cors: To allow different origins (Avoid Preflight Request Failed or CORS )

Objection: ORM that helps create database queries easily (Knex supports Objection)

MySQL/MySQL2: Drivers for MySQL

Now Let’s Create the entry point (index.js file):

We create our route ‘/’ that returns ‘It`s Working’ from http://localhost:3000 using an arrow function.

The argument ctx is a context, an object that provides a list of properties like request, response body, headers, etc (Imagine a waiter coming forth with food & bill and going back with money & tips). We change the response body to using ctx.body to say ‘It`s Working’ .

To be continued with Objection.js Syntax, modules, and middleware …

--

--

Syed Riyaz Uddin

UX Designer, Programmer and App Developer. Aiming to make things simple, beautiful and fun | Connect with me @ spotverge.com