Node.js REST API packed as Snap

Hi, I’m new using Ubuntu Core and Snap development, I would like to have some guidance on how to create a Snap that contain a REST API built in Node.js I created a very very simple API:

const express = require('express');

const app = express();

var cors = require('cors');

const port = 3000;

app.use(cors());

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

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

I don’t really know how to configure the snapcraft.yaml file to make this work, I check there is an npm plugin but it does not work for me, also I don’t know how to setup the snap so it runs like a deamon and in start it runs npm run start from a package.json script.

I will really appreciate any help you can provide me. Thanks in advanced

– EDIT –

I’m trying with the snapcraft.yaml with this configuration:

name: snap-hello-api # you probably want to 'snapcraft register <name>'
base: core22 # the base snap is the execution environment for this snap
version: '0.1' # just for humans, typically '1.2+git' or '1.3.2'
summary: Node.js REST API packaged as snap # 79 char long summary
description: |
  Snap that publish a Node.js REST API that listen for GET request

grade: devel # must be 'stable' to release into candidate/stable channels
confinement: devmode # use 'strict' once you have the right plugs and slots

parts:
  snap-hello-api:
    plugin: npm
    npm-node-version: 18.16.0
    source: .
apps:
  snap-hello-api:
    daemon: simple

In case someone is wonder this same question, I did make it work and it was absolutely simpler than expected:

This is my snapcraft.yaml configuration:

name: snap-hello-api
base: core22
version: '0.1'
summary: Node.js REST API packaged as snap # 79 char long summary
description: |
  Snap that publish a Node.js REST API that listen for GET request

grade: devel 
confinement: devmode

parts:
  snap-hello-api:
    plugin: npm
    npm-include-node: true
    npm-node-version: 18.16.1
    source: .
apps:
  snap-hello-api:
    command: bin/start
    daemon: simple

Two other couple of things to make it work was, in the package.json include “bin”

"bin": {
    "start": "app.js"
  },

And in the app.js include the header:

#! /usr/bin/env node

The example can be found in this public repo: https://github.com/jperera84/snap-hello-api

I hope this help!!

2 Likes