A Nodejs Microservice Template for Rapid Prototyping
The template described in this article would be a good starting point for any application, including commercial services destined for AWS or Azure. But it is lightweight enough to be used for quick experiments and prototypes served by, say, a Raspberry Pi. And it is simple enough to be used and customized by developers with limited back-end experience.
Key features include:
- An express Web server
- A ws WebSocketServer
- Protocol upgrade for url-based socket connections
- JWT authentication and permission management
- A mock JWT authentication handler (auth server)
- A mini dynamic Web site handler (using Handlebars templates and Bootstrap 5)
- Packaging with webpack
- A node cli client for testing socket connections
- A Dockerfile for easy container deployment
The microservice architecture is described in described in Figure 1:
Install, Build and Start
You can get the microservice template running in just a few steps. First, clone the microservice-template repo (on github)
git clone git@github.com:wwlib/microservice-template.gitThen install, build and start:
cd microservice-template
npm install
npm run build
npm run startYou should see a message like this indicating that the service is running on port 8000:
> microservice-template@0.0.1 start /Users/andrewrapo/github/wwlib/microservice-template
> node -r dotenv/config dist/index.js(USE_AUTH !== true) so NOT using mock JWT auth.
HTTP/WS server is ready and listening at port 8000!
Note: By default, JWT auth is disabled. This is fine for now. See the instructions for turning it the section below about Authentication and Permissions.
Testing with Curl
The easiest way to test the service is by using Curl from a terminal window. The following curl command will make a POST request to http://localhost:8000/post:
curl --location --request POST 'http://localhost:8000/post' \
--header 'Content-Type: application/json' \
--data-raw '{
"utterance": "hello"
}'The default/example response from the server is to echo the input data along with a status message and the current userId if authentication is enabled:
{"status":"OK","utterance":"hello","userId":""}See more about this response in the section below about HTTP Handlers
Testing with the Browser
Entering this URL into your browser, http://localhost:8000/get?utterance=greetings , will make a GET request to the service and similarly return:
{"status":"OK","utterance":"greetings","userId":""}Testing with the Socket CLI Client
You can also test the service using the node socket cli in the tools folder:
cd tools
node socket-cli.jsThis will start a socket session. Anything you type at the “>” prompt will be echoed:
Testing using the embedded Web Site
The microservice-template serves a simple Web site with a few default routes.
Dashboard
The default route serves a placeholder Dashboard: http://localhost:8000/
Also: http://localhost:8000/dashboard/
The example Dashboard displays one real stat: the number of requests made the the service. The Activity graph displays a set of fake/placeholder values that are generated on the server. The Events table is a static placeholder.
Console
The example console accepts commands that can control the service. One example command is implemented. Typing “reset” into the command field and clicking the Submit button will reset the counter (on the server) keeping track of the number of requests that have been made. If you then return to the Dashboard you will see that the Request Count stat has been reset.
Authentication and Permissions
The microservice -template uses a JWT (JSON Web Token) mechanism for managing authentication and permissions (authorization). JWT is a widely used auth mechanism because it is ‘stateless’ — i.e. it does not require session data to be maintained by the server. Session data, like permissions, is maintained in an access token which is included in the header of all requests to the microservice. When auth is enabled, requests to the microservice are scrutinized before processing the transaction. The access token is decoded and validated using a secret key known only to the microservice. Then the permissions specified in the payload of the decoded token are compared to the permissions required by the service for each transaction type. If the token is valid AND contains the required permissions, the transaction is allowed and a response is sent to the client. Otherwise an error response is returned.
Get Andrew Rapo’s stories in your inbox
Join Medium for free to get updates from this writer.
To communicate successfully with the microservice, a client — i.e. a Web page — must first sign in and get an access token. Usually, a client will send username/password credentials to an auth service, get a token, and then use that token to make requests to the microservice. The microservice then checks with the auth service to validate the client’s token before fulfilling the request.
To keep this example as simple as possible, the microservice-template acts as its own auth server via its /auth route.
To see the JWT auth in action, copy .env-example to .env and make sure the USE_AUTH property is set to true (USE_AUTH=true)
SERVER_PORT=8000
USE_AUTH=trueThen start the service and make sure you see, using mock JWT auth.
$ npm run start> microservice-template@0.0.1 start /[...]/microservice-template
> node -r dotenv/config dist/index.js(USE_AUTH === true) so using mock JWT auth.
HTTP/WS server is ready and listening at port 8000!
Now go to http://localhost:8000 which should redirect to the signin page:
Enter any username and password (the mock JWT auth will accept any credentials) and you should be redirected to the dashboard page.
There is a fair amount going on to make this work. The call to /auth returns an access token which gets saved as an HTTP-only cookie in the browser. This cookie is called access_token. A second refresh token is also returned and saved in a cookie called refresh_token. The access_token cookie is set to expire in 1 minute. When it does expire, the refresh token will be used to request a new access token. The refresh token has a longer life, 1 day, and will be remembered even if the browser is closed. If both the access token and the refresh token expire, the user will be prompted to sign in again. There are many examples and tutorials online that provide a more detailed explanation. A couple of good ones include:
- Using Cookies with JWT in Node.js
- LocalStorage vs. Cookies: All You Need to Know About Storing JWT Tokens Securely in the Front-End
You can get an access token using curl:
curl --location --request POST 'http://localhost:8000/auth' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "user1",
"password": "12345!"
}'If you make a POST request to /auth using Postman you will get a payload that includes bot the access_token and the refresh_token:
{"message":"Logged in successfully.","access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMSIsImF1dGgiOnsicGVybWlzc2lvbnMiOlt7InNjb3BlcyI6WyJyZWFkIl0sInJlc291cmNlIjoiZXhhbXBsZSJ9XX0sImlhdCI6MTY1NTE1MzIwMiwiZXhwIjoxNjU1MTUzMjYyfQ.L7H7ivCKP0C8lVWqcGdKAY6DRaooowb44V7XUI_bBfA","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMSIsImlhdCI6MTY1NTE1MzIwMiwiZXhwIjoxNjU1MjM5NjAyfQ.tIbZOehAHw_pDx4KneC7YlSSIC6pPaWnpxu9ArDD0pM","user_id":"user1"}You can then use the access token in Postman to make an authenticated request. For example: http://localhost:8000/get?utterance=hello
JWT.io
To get a better look at the way tokens are managed, you can go to https://jwt.io/ and paste the access_token into the Encoded field:
The decoded token includes the permissions that are used by the express auth function (in ExpressAuthFunctions.ts). When the routes are added (in index.ts) a list of required premissions can be included for each route. To illustrate, several of the protected routes have example:read in their permissions list (see Figure 11, below). This means that the permissions object in the decoded access token must include the read scope for the resource named, example. In a more complex service, there would be multiple resources with multiple scopes. These are defined by the service author.
Source Code
Figure 12 shows a map of the microservice source code.
HTTP Handlers
As demonstrated above, the HTTP example handlers (ExampleHandlers.ts) implement routes for GET and POST requests. The /get route handles GET requests where parameters are encoded in the query string, like: http://localhost:8000/get?utterance=hello The response is a JSON object that echos the utterance parameter and includes the signed-in user id if it is available. The /post route handles POST requests where the parameters are included in the request body.
Socket Handlers
As demonstrated above, the example socket handlers (WsExampleHandlers.ts) includes an implementation of a route, /ws-echo, which opens a socket connection that echos any messages it receives.
Site Handlers
As demonstrated above, the example site handers (site/SiteHandler.ts) implement the handlers that serve the /dashboard, /console and /signin page routes. These pages are dynamically rendered using Handlebars templates which include variables and expressions that are evaluated at render time.
Client Auth (JWT)
As described above, the express auth functions (EspressAuthFunctions.ts) are used to protect certain routes by validating the access_token and checking to make sure that any required permissions are granted in the token.
Auth Server (JWT)
The mock auth handlers (MockAuthHandlers.ts + JwtAuth.ts) implement the /auth route used by the signin page to get an access token.
Docker
The Dockerfile used to build and run a containerized version of the microservice-template using the following npm commands:
npm run docker:buildnpm run docker:run
Util Wrappers
The express route wrapper (ExpressRouterWrapper.ts) provides convenience functions that make it easy to set up protected HTTP routes.
The socket server wrapper (WebSocketServerWrapper.ts) provides convenience function for setting up protected socket routes.
Tools
The socket-cli.js tool is used to test the microservice-template’s socket connection — with or without authentication.
Customization (i.e. Time Server)
As its name implies, the microservice-template project is only a starting point. The project is designed to make customization easy. As a quick example, the steps to add a time server feature (route) would be:
Add a /time handler (i.e. handlers/TimeHandler.ts) like:
import { Request, Response } from 'express'
import { StatusCodes } from 'http-status-codes'export const TimeHandler = (req: Request, res: Response) => {
const time = new Date().toLocaleString()
res.status(StatusCodes.OK).json({ time })
}
Add an export to handlers/index.ts
export * from './TimeHandler'Add a /time route to the main /index.ts
expressRouterWrapper.addGetHandler('/time', handlers.TimeHandler, ['example:read'])Rebuild and restart the service:
npm run build
npm run startThe new http://localhost:8000/time route should return the current time, for example:
{"time":"6/13/2022, 8:10:28 PM"}For another customization example see: Using Microsoft Orchestrator for Intent Recognition and Dispatch to Luis
Conclusion
The microservice-template is an easy-to-customize starting point for a service that may start out as a rapid prototype but grow into something more.










