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
- Installed Express to handle API routes
- Created a
server.js
file with routes - Hooked up CLI app logic to route handlers
- Initialized Fly.io app with “fly launch”
- Deployed app using
fly deploy
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:
- This will generate a
fly.toml
file with your app configuration. - it will auto detect and create a Dockerfile for you
4.3 Deploy
Deploy your app:
fly deploy
Your REST API will now be live on Fly.io!