Skip to content

how to package any nodejs app to rest api

Posted on:November 22, 2023 at 12:00 AM

How to Package a Node.js CLI App as a REST API and Deploy to Fly.io

Overview

This guide covers how to take an existing Node.js command line interface (CLI) application and expose it as a REST API using Express, then deploy it to Fly.io.

TLDR

Steps

1. Install Express

Install Express in your Node.js project:

npm install express

2. Create a server.js File

Create a server.js file that will handle the API routes:

// server.js

const express = require('express');
const app = express();

// API route
app.get('/api', (req, res) => {
  // Call CLI app logic
  const output = myCliApp.run(); 
  return res.json(output);
});

app.listen(3000, () => {
  console.log('API server listening on port 3000');
});

3. Hook Up CLI App Logic

Import your CLI app logic and call it from the API route handler:

+ const myCliApp = require('./myCliApp');

app.get('/api', (req, res) => {
+ const output = myCliApp.run();
  return res.json(output); 
});

4. Deploy to Fly.io

4.1 Initialize an app use fly cli

In your project directory, run:

fly launch

it will interview you and generate the following:

4.3 Deploy

Deploy your app:

fly deploy

Your REST API will now be live on Fly.io!