Introduction
This guide will serve as an illustration on how to use the Node.js and Serverless frameworks to create a microservice completely local to your development environment. I’ve deployed Node.js and Serverless with AWS Lambda in production with much success, but if you simply don’t have a personal AWS account and wanted to test an idea out then offline deployment allows for greater accessibility.
Frameworks
Serverless is an excellent tool that excels with microservices (think AWS Lambda or Google’s cloud functions) that is fairly intuitive and comes with a couple of features OOTB.
We’ll also be using Nest.Js, a Node.js framework that was recommended for it’s friendliness and it’s production ready scope.
Setting up the environment
Let’s begin with setting up our development environment. I strongly recommend npm
to install the required packages. As for an IDE, my favorite is Webstorm however Visual Studio Code provides a nice free alternative.
Installing Nest.Js & instantiating the project:
npm install -g @nestjs/cli
nest new local-microservice
(Select npm
as the package manager)
This will create a new directory local-microservice
where we’ll be doing most of our work from now on. Navigate into it.
Installing Serverless and offline plugin:
npm install -g serverless
npm install --save-dev serverless-offline plugin
This allows us to run the function offline.
Installing some dependencies to configure for the AWS Lambda context:
npm install --save-dev aws-lambda
npm install --save @types/aws-lambda
npm install --save-dev aws-serverless-express
npm install --save @types/aws-serverless-express
Integrating Nest.Js with Serverless
Instantiating Nest.Js gives us a nice little file in src, main.ts
. I’d advocate for deleting it, as it won’t be used for the context of serverless or deployment and this reduces dead code (however it will be necessary to keep if you wish to still run nest
).
You can easily add the new entry point with two files, both in src:
Now that we have the 2 files needed to create an entry point, we need to actually specify it in serverless’s configuration file. This is placed at the root:
Build & Run
All that is left is to compile and run the Lambda simulator:
npm run build
sls offline start
If you head on over to your favorite browser and navigate to http://localhost:3000/dev, you’ll see a very familiar message!
Conclusion
All in all, this should be a fairly quick and painless way to spin up a local microservice using Node.js and Serverless. In the future, I may expand upon greater simulation capabilities (for example, there’s a plugin to simulate AWS’s DynamoDB locally!).
You can view the full codebase here if you’d like to take a deeper look. If you have any questions let me know and I’d be happy to help out!