DEV Community

Cover image for Adding pub/sub to an Express application.

Posted on • Updated on

Adding pub/sub to an Express application.

In this blog post, we'll take a deeper look at how you can scaffold a new cloud application and take advantage of resources like topics, queues, and buckets in your Express applications.

Essential Tools and Services

To follow through and successfully complete this guide, you'll need to have the following tools and services installed and set up:

Setting up Your Project

Our first step will be to initialize a new Nitric project and add Express.js to it. Open a terminal and execute the following commands:

nitric new
? What is the name of the project? express-example
? Choose a template: official/JavaScript - Starter

# Navigate into your newly created project directory and install dependencies
cd express-example
yarn install

# Add express to your project
yarn add express
Enter fullscreen mode Exit fullscreen mode

Now, open the project in your preferred code editor. Your project structure should resemble the following:

├── functions
│   ├── hello.js
├── node_modules
│   ├── ...
├── .gitignore
├── index.js
├── nitric.yaml
├── package.json
└── yarn.lock
Enter fullscreen mode Exit fullscreen mode

You might notice a functions folder in the project structure. By default, Nitric anticipates the entry-point code for your application to reside here. However, this convention is flexible; you can modify it according to your application's requirements.

For this guide, let's replace the functions folder with a single entry-point file named app.js. Execute the following commands to achieve this:

rm ./functions/hello.js
touch ./functions/app.js
Enter fullscreen mode Exit fullscreen mode

Next, we'll add some express code to kickstart our application:

import express from 'express'
import { http } from '@nitric/sdk'

const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')

Enter fullscreen mode Exit fullscreen mode

In the code snippet above, if you're familiar with Express.js, you'll notice we didn't use app.listen. Instead, we employed the Nitric http function. This function handles the responsibility of binding the application to the appropriate port for each environment, thereby eliminating the need for app.listen.

With this setup, your Express.js application is ready for local testing. By default, the project comes with a dev script that you can run to start the local development server:

yarn dev
Enter fullscreen mode Exit fullscreen mode

If your setup is correct, part of the output should resemble:

SUCCESS  Started Local Services! (1s)
Local running, use ctrl-C to stop

Proxy | Endpoint
8000  | http://localhost:4001

Dev Dashboard | http://localhost:49152
Enter fullscreen mode Exit fullscreen mode

Now, your Express application is running locally, with Nitric acting as a proxy. The app is available at port 4001, and you can test it using another terminal or web browser. Run the following command in another terminal:

curl localhost:4001
Hello World!
Enter fullscreen mode Exit fullscreen mode

Enhancing Your Express.js Application with cloud resources using Nitric

With the basic Express.js application up and running, let's explore how to extend its functionality with Nitric. For instance, we'll add a pub/sub topic that will allow us to execute tasks in the background while still maintaining quick HTTP API response times.

Update your app.js file with the following code:

import express from 'express'
import { http, topic } from '@nitric/sdk'

const app = express()
const workRequests = topic('work-requests').for('publishing')

app.get('/', async (req, res) => {
  await workRequests.publish()
  res.send('Hello World!')

Enter fullscreen mode Exit fullscreen mode

In the updated code above, we introduce a workRequests topic that our application publishes. We also create a new function to handle the background work:

touch functions/worker.js
Enter fullscreen mode Exit fullscreen mode

The worker.js file will contain the following code:

import { topic } from '@nitric/sdk'

const sleep = (ms) => new Promise((res) => setTimeout(res, ms))

topic('work-requests').subscribe(async (ctx) => {
  console.log('Starting new request')
  // Wait for 2 seconds to simulate a long-running task
  await sleep(2000)
  console.log('Request processed')
Enter fullscreen mode Exit fullscreen mode

When you navigate to localhost:4001 in your browser, you should notice that the console outputs two lines, with a two-second delay between them, which indicates the simulated work request:

Starting new request
Request processed
Enter fullscreen mode Exit fullscreen mode

You should note that even though the background worker takes two seconds to finish, the HTTP request GET: / still returns instantly.

Deployment to the Cloud

Nitric simplifies the process of deploying your application to the cloud. It negates the need for manual cloud deployment processes or the use of external solutions like Terraform.

To facilitate the deployment, we'll create a stack. A stack provides Nitric with the configuration necessary for a specific cloud instance of your project, such as the provider and the region.

Let's create a new stack for AWS:

nitric stack new
? What do you want to call your new stack? dev
? Which Cloud do you wish to deploy to? aws
? select the region us-east-1
Enter fullscreen mode Exit fullscreen mode

The nitric stack new command will create a file named nitric-dev.yaml, containing:

name: dev
provider: nitric/aws@0.30.0
region: us-east-1
Enter fullscreen mode Exit fullscreen mode

Now, you can deploy your application to the cloud using the following command:

nitric up
Enter fullscreen mode Exit fullscreen mode

After successful deployment, you can access your Express.js + Nitric application in the cloud using the API Gateway URL provided in the up command's output.

When you're done with the cloud deployment, you can decommission it using the nitric down command.

Further Exploration

Watch a video about our frameworks support.

Now that you understand the basics, consider exploring other Nitric resources available to enhance your app. These resources include:

Each of these can be added to your application with only a few lines of code.

Happy coding!

Top comments (1)

rsiv profile image