How to persist data in a snap using NodeJS

I am having some issues keeping a config file that is written the first time the snap runs. I am using NodeJS to handle this and I am thinking there must be another was (as it’s not working)…

Here is what the NodeJS code does:

  1. It Checks fs.existsSync(process.env.SNAP_COMMON + '/config.json') to see if my config file is there.

  2. If it does not find it, the file is then created with fs.writeFile(process.env.SNAP_COMMON + '/config.json', {some json}, 'utf8', callback(err) ). The config file holds an ID from a web service that can only be requested once. If the request is made again it will return a new ID.

  3. Then the rest of my app runs as normal.

NOTE: All of this is working - if the file does not exist it will create it, and write to it. My issue is when the device is restarted or unplugged then powered back on it goes to create a new config file thus grabbing a new ID.

So my question: How should I be storing and persisting configuration data that should only be generated once in the lifetime of the device (the configuration file should not be overwritten on refresh or even a new version of the snap it should persist after the first creation)?

Should I be creating the config files with a hook? Any help would be wonderful!

Thanks for the help in advance!!

I was able to solve this by NOT creating and checking for the config files in NodeJS and moving all of that logic to an install hook (

So now my Install hook will check for the config file and create it if its not there, then I allow NodeJS to write to that file later so I can still make all the HTTP requests in NodeJS and not in Bash. Below is my Install hook, dont forget to make it executable.

This file is located at snap/hooks/install

set -e


if [ ! -f $CONFIG_FILE ]; then
    # File Not Found, Create it
    echo '{}' > $CONFIG_FILE

Hope this helps someone!

1 Like

you can indeed also ship it in $SNAP and just copy it over to $SNAP_COMMON (or $SNAP_DATA) if it doesnt exist… i.e. to ship the correct upstream defaults from a project you package.