Host discord.js bot on NixOS server?

Does anyone have an idea how I could host my discord.js bot on a nixos server? The first step seems simple, I specify a systemd sercive with a startup command to keep the bot up all the time. But now I have the problem that there is the config.json file where I have client token, guild token and bot token and i somehow need to get that on the server. Plus the whole codebase it is reliant on

so to make it start I normally run the command node index.js , but for that I would now need the whole code on the server and also the secret tokens

I think I have to somehow build it for the nix store so I can start the bot in ExecStart but there is nothing that needs to be built for the bot…

Here, to explain better:

 systemd.services.bot = {
    description = "discord bot";
    wantedBy = ["multi-user.target"];
    after = ["network-online.target"];
    serviceConfig = {
      ExecStart = "node index.js";
    };
  };

but yeah the node index.js has no clue what codebase to do that for and the secrets are also nowhere.

This is my current flake for the discord bot, so just a devShell …

{
  description = "JavaScript development environment";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs";
  };

  outputs = { self, nixpkgs }:
    let
      # Systems supported
      allSystems = [
        "x86_64-linux"
        "aarch64-linux"
        "x86_64-darwin"
        "aarch64-darwin"
      ];
      
      forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
        pkgs = nixpkgs.legacyPackages.${system};
      });
    in
    {
      devShells = forAllSystems ({ pkgs }: {
        default = pkgs.mkShell {
          packages = with pkgs; [
            nodejs_18
          ];
        };
      });
    };
}

I would package the bot with buildNpmPackage, then use that package with the systemd unit. This avoids any build issues and abstracts away the problem of “how do I run this?”.

You should probably use some sort of secret management scheme for the tokens like agenix or sops-nix and use those secrets to populate a config.json file. Adding support for flags or environment variables would mean you could set up the tokens in the systemd unit.

1 Like