Deploy a Secure Node.js LLM Web App on Ubuntu 24.04

    This tutorial explains how to deploy a minimal Express-based Node.js web app on Ubuntu 24.04 that forwards user messages to an OpenAI-compatible LLM API. It covers non-root user setup, SSH hardening, UFW configuration, installing Node.js 24 with nvm, dependency troubleshooting, protecting API keys with environment files, testing API connectivity, accessing the app through an SSH tunnel, running it as a systemd service, and verifying the final deployment.

    Deploy a Secure Node.js LLM Web App on Ubuntu 24.04

    Introduction: What This Tutorial Covers

    Many developers want to run a chat page on their own server and forward user input to an LLM API. This approach has two advantages: the API key stays on your own machine, and the interface can be modified as needed. In practice, the main difficulties usually involve the Node.js version, server permissions, secret management, and network access.

    This article does not rely on a third-party scaffold. Instead, it uses Express to build a minimal web app of about 60 lines. The page provides an input box, and the server forwards the input to any OpenAI-compatible endpoint. An OpenAI-compatible endpoint means the request URL ends with /chat/completions and the request body format matches the official OpenAI format. Many LLM platforms provide this type of endpoint.

    Target environment: an Ubuntu 24.04 LTS server and a local computer with an SSH client (Windows users can use PowerShell or WSL). All operations in this article are performed as a regular user, not by logging in directly as root.

    1. Prepare a Regular User and a Security Baseline

    If you currently have only a root account, first create a dedicated regular user for deployment and running the app.

    1. # Run on the server; set a password when prompted
    2. sudo adduser deploy
    3. # Grant sudo access only for privilege escalation when needed
    4. sudo usermod -aG sudo deploy

    Next, copy your local SSH public key to the server. If you do not have a key yet, generate one first with ssh-keygen -t ed25519.

    1. # Run on your local computer; replace <server-IP> with the actual address
    2. ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@<server-IP>

    Open a new terminal and confirm that you can log in with the key without a password. Only proceed after confirming this works; otherwise, you may lock yourself out of the server.

    1. ssh deploy@<server-IP>

    After confirming login works, disable password authentication and root remote login. Ubuntu 24.04 reads configuration files under /etc/ssh/sshd_config.d/, and for the same parameter, the first value read takes precedence. Cloud host images often include 50-cloud-init.conf, which enables password authentication. Therefore, this article names the configuration file 10-hardening.conf so that it takes effect earlier.

    1. sudo tee /etc/ssh/sshd_config.d/10-hardening.conf > /dev/null <<'EOF'
    2. PasswordAuthentication no
    3. PermitRootLogin no
    4. EOF
    5. # Check the configuration syntax, then reload the service only if it passes
    6. sudo sshd -t && sudo systemctl reload ssh
    7. # Confirm the final effective values
    8. sudo sshd -T | grep -iE 'passwordauthentication|permitrootlogin'

    The output should be passwordauthentication no and permitrootlogin no.

    Finally, configure the firewall. Deny all inbound connections by default and allow only SSH. The web app in this article will not expose a port to the public internet. If your SSH service uses a custom port, replace OpenSSH with the corresponding port number, such as 2222/tcp; otherwise, your current connection will be disconnected.

    1. sudo ufw default deny incoming
    2. sudo ufw default allow outgoing
    3. sudo ufw allow OpenSSH
    4. sudo ufw enable
    5. sudo ufw status verbose

    default allow outgoing is necessary because the server needs to initiate requests to the LLM API.

    2. Install and Verify Node.js with nvm

    The Node.js version in the Ubuntu software repositories is often outdated. It is recommended to install Node.js with Node Version Manager (nvm), which installs Node.js and global packages under the user’s home directory without requiring sudo.

    At the time of writing, Node.js 24 is the current Active LTS version, and Node.js 22 has entered maintenance. For new projects, choose 24. For the nvm version number, refer to the Releases page of the official repository; the example below uses v0.40.3.

    1. curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
    2. # Reload the shell configuration. If you use zsh, change this to source ~/.zshrc
    3. source ~/.bashrc
    4. nvm install 24
    5. nvm alias default 24
    6. # Verify the version and paths
    7. node -v
    8. npm -v
    9. which node
    10. npm root -g

    Expected results: node -v outputs v24.x.x. which node outputs a path beginning with /home/deploy/.nvm/versions/node/. npm root -g outputs lib/node_modules under the same version directory. This path will be useful later when troubleshooting global installation issues.

    If which node shows /usr/bin/node, the system-provided Node.js is still ahead in the PATH. Run source ~/.bashrc again, or check whether the nvm loading code in ~/.bashrc is complete.

    3. Create the App and Troubleshoot Installation Issues

    The project structure is as follows:

    1. llm-web/
    2. ├── .env
    3. ├── .gitignore
    4. ├── .nvmrc
    5. ├── package.json
    6. ├── server.js
    7. └── public/
    8. └── index.html

    Create the directory and install dependencies. .nvmrc records the Node.js major version. Later, when you enter this directory, run nvm use to switch to the same version.

    1. mkdir -p ~/llm-web/public && cd ~/llm-web
    2. echo "24" > .nvmrc
    3. npm init -y
    4. npm pkg set type=module
    5. npm pkg set scripts.start="node --env-file=.env server.js"
    6. npm install express@5

    The --env-file parameter has been supported since Node.js 20.6, so there is no need to install dotenv separately.

    Create the server file server.js. It reads environment variables, forwards user messages to the model endpoint, and does not write the API key to logs.

    1. import express from 'express';
    2. const {
    3. LLM_BASE_URL,
    4. LLM_API_KEY,
    5. LLM_MODEL,
    6. PORT = '3000',
    7. HOST = '127.0.0.1',
    8. } = process.env;
    9. if (!LLM_BASE_URL || !LLM_API_KEY || !LLM_MODEL) {
    10. console.error('Missing LLM_BASE_URL, LLM_API_KEY, or LLM_MODEL. Check the .env file.');
    11. process.exit(1);
    12. }
    13. const app = express();
    14. app.use(express.json({ limit: '32kb' }));
    15. app.use(express.static('public'));
    16. app.get('/healthz', (req, res) => res.json({ ok: true }));
    17. app.post('/api/chat', async (req, res) => {
    18. const message = typeof req.body?.message === 'string' ? req.body.message.trim() : '';
    19. if (!message || message.length > 4000) {
    20. return res.status(400).json({ error: 'Message must not be empty and must not exceed 4000 characters' });
    21. }
    22. try {
    23. const upstream = await fetch(`${LLM_BASE_URL}/chat/completions`, {
    24. method: 'POST',
    25. headers: {
    26. 'Content-Type': 'application/json',
    27. Authorization: `Bearer ${LLM_API_KEY}`,
    28. },
    29. body: JSON.stringify({
    30. model: LLM_MODEL,
    31. messages: [{ role: 'user', content: message }],
    32. }),
    33. signal: AbortSignal.timeout(30_000),
    34. });
    35. if (!upstream.ok) {
    36. console.error('Upstream returned status code:', upstream.status);
    37. return res.status(502).json({ error: `Model endpoint returned ${upstream.status}` });
    38. }
    39. const data = await upstream.json();
    40. res.json({ reply: data.choices?.[0]?.message?.content ?? '' });
    41. } catch (err) {
    42. console.error('Model call failed:', err.name, err.message);
    43. res.status(502).json({ error: 'Model call failed. Check the server logs.' });
    44. }
    45. });
    46. app.listen(Number(PORT), HOST, () => {
    47. console.log(`Listening on http://${HOST}:${PORT}`);
    48. });

    Create the frontend page public/index.html:

    1. <!doctype html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="utf-8">
    5. <title>LLM Test Page</title>
    6. </head>
    7. <body>
    8. <textarea id="msg" rows="4" cols="60"></textarea><br>
    9. <button id="send">Send</button>
    10. <pre id="out"></pre>
    11. <script>
    12. document.getElementById('send').onclick = async () => {
    13. const r = await fetch('/api/chat', {
    14. method: 'POST',
    15. headers: { 'Content-Type': 'application/json' },
    16. body: JSON.stringify({ message: document.getElementById('msg').value }),
    17. });
    18. const d = await r.json();
    19. document.getElementById('out').textContent = d.reply ?? d.error;
    20. };
    21. </script>
    22. </body>
    23. </html>

    Add .gitignore to prevent secrets and dependencies from being committed to the code repository:

    1. printf ".env\nnode_modules/\n" > .gitignore

    Troubleshooting in this directory usually centers on the installation phase. If npm install fails, use the table below.

    Symptom Common cause Resolution
    EACCES: permission denied The system Node.js is being used, or sudo npm was used by mistake Use which npm to confirm the path is under ~/.nvm, and do not use sudo npm install -g
    ENOTEMPTY A previous installation was interrupted, leaving an incomplete directory First run ls "$(npm root -g)" to inspect leftovers, then delete only the package directory in the error path, not the entire node_modules
    SyntaxError or --env-file is not recognized Node.js version is lower than 20.6 Run node -v, then use nvm use 24 to switch versions
    deprecated warning A dependency’s subpackage has been marked deprecated by its author As long as npm install exits with code 0, the warning does not affect operation. It can be removed later by upgrading dependencies
    UNABLE_TO_VERIFY_LEAF_SIGNATURE or self-signed certificate A proxy in the network environment is replacing certificates Import the enterprise root certificate and specify it with NODE_EXTRA_CA_CERTS=/path/to/certificate.pem. Do not set NODE_TLS_REJECT_UNAUTHORIZED=0

    After installation, use npm ls express to confirm the dependency version. The output should be express@5.x.x.

    4. Configure the LLM API and Verify Connectivity

    Create the configuration file. The command below uses nano, which avoids writing the key into command-line history.

    1. nano .env

    Fill in the file with the following content. LLM_BASE_URL should follow the provider’s documentation; the OpenAI-compatible format usually looks like https://provider-domain/v1. The model name must also exactly match the name in the provider’s documentation, including capitalization.

    1. # LLM API base URL; do not end with a slash
    2. LLM_BASE_URL=https://provider-domain/v1
    3. # API key created in the provider console
    4. LLM_API_KEY=sk-replace-with-your-key
    5. # Model name, for example the model ID in the provider documentation
    6. LLM_MODEL=replace-with-model-id
    7. # Listen only on the local loopback address
    8. PORT=3000
    9. HOST=127.0.0.1

    After saving, tighten file permissions so that only the file owner can read and write it:

    1. chmod 600 .env
    2. ls -l .env

    The output should begin with -rw-------.

    Before starting the app, test the model endpoint directly. This separates network, key, and application code issues.

    1. # Load variables from .env into the current shell and disable automatic export
    2. set -a; . ./.env; set +a
    3. curl -sS -m 30 "$LLM_BASE_URL/chat/completions" \
    4. -H "Content-Type: application/json" \
    5. -H "Authorization: Bearer $LLM_API_KEY" \
    6. -d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}]}"

    If the returned JSON contains a choices field, the endpoint is working. If one of the following errors appears, troubleshoot in the corresponding direction:

    • 401 or 403: The API key is incorrect, expired, disabled, or the account quota is exhausted. Check whether .env contains extra spaces or line breaks.
    • 404: LLM_BASE_URL is missing /v1, or LLM_MODEL is misspelled.
    • curl: (28) Operation timed out: The server cannot access the external network. Check outbound firewall and proxy settings, and confirm that default allow outgoing in ufw is active.
    • curl: (60) SSL certificate problem: This is the same certificate issue as in the previous table; handle it in the same way.

    After the endpoint test passes, start the app and verify it locally on the server:

    1. npm start

    In another session, run:

    1. curl -s http://127.0.0.1:3000/healthz
    2. # Output: {"ok":true}
    3. curl -s -X POST http://127.0.0.1:3000/api/chat \
    4. -H "Content-Type: application/json" \
    5. -d '{"message":"hello"}'

    If the second command returns a reply field, the app can forward requests successfully. After confirming this, press Ctrl+C to stop the foreground process; next, systemd will manage it.

    5. Access Through an SSH Tunnel and Set Up Persistent Operation

    The app listens on 127.0.0.1:3000, so it cannot be accessed directly from external networks. This is intentional. Access is provided by creating an SSH tunnel from your local computer.

    Run the following command on your local computer. -N means only forward ports and do not open a remote shell.

    1. ssh -N -L 8080:127.0.0.1:3000 deploy@<server-IP>

    Keep this window running, then open http://localhost:8080 in your local browser. All traffic is transmitted through the encrypted SSH channel.

    After the tunnel is established, you can confirm the service listening address on the server with:

    1. ss -tlnp | grep 3000

    The address in the output should be 127.0.0.1:3000. If it shows 0.0.0.0:3000, the HOST setting in .env is incorrect; modify it and restart the service.

    Configure a systemd Service

    If you run npm start manually, the app stops when you close the terminal. systemd can start the app at boot and restart it automatically after a crash.

    First, get the absolute path to Node.js. systemd does not load nvm’s shell configuration, so an absolute path is required.

    1. which node

    Assume the output is /home/deploy/.nvm/versions/node/v24.x.x/bin/node. Create the service file:

    1. sudo nano /etc/systemd/system/llm-web.service

    Write the following content, replacing the path in ExecStart with the output from the previous step:

    1. [Unit]
    2. Description=LLM Web App
    3. After=network-online.target
    4. Wants=network-online.target
    5. [Service]
    6. Type=simple
    7. User=deploy
    8. WorkingDirectory=/home/deploy/llm-web
    9. ExecStart=/home/deploy/.nvm/versions/node/v24.x.x/bin/node --env-file=.env server.js
    10. Restart=on-failure
    11. RestartSec=5
    12. NoNewPrivileges=true
    13. PrivateTmp=true
    14. [Install]
    15. WantedBy=multi-user.target

    Enable and start the service:

    1. sudo systemctl daemon-reload
    2. sudo systemctl enable --now llm-web
    3. systemctl status llm-web --no-pager

    View logs:

    1. # Last 50 log lines
    2. journalctl -u llm-web -n 50 --no-pager
    3. # Follow logs in real time
    4. journalctl -u llm-web -f

    If the service restarts repeatedly, check the first error in the logs. It is usually caused by a missing variable in .env, an incorrect Node.js path, or a port already in use.

    Choosing an Access Method

    An SSH tunnel is suitable for personal use or a small number of users. It does not require a domain name or certificate, and the service is not exposed to the public internet. If multiple people need to access it directly through a browser, you can use Nginx as a reverse proxy and configure a Let’s Encrypt certificate and login authentication. In that case, the app should still listen only on 127.0.0.1, while Nginx provides HTTPS externally. This approach requires opening port 443 and taking on the maintenance work of certificate renewal and authentication management.

    6. Checklist

    After deployment, confirm the following items one by one:

    • The deploy user can log in with a key, root remote login is disabled, and password authentication is disabled.
    • sudo ufw status allows only the SSH port.
    • node -v outputs v24.x.x, and which node is under ~/.nvm.
    • .env permissions are -rw-------, and the file is included in .gitignore.
    • A direct call to the model endpoint returns JSON containing choices.
    • ss -tlnp | grep 3000 shows 127.0.0.1:3000.
    • systemctl status llm-web shows active (running).
    • After creating the SSH tunnel locally, http://localhost:8080 can send messages and receive replies normally.

    If an API key ever appears in chat history, screenshots, or a code repository, revoke it immediately in the provider console and generate a new one. Also set a usage limit in the console to control the cost risk of unexpected calls.

    After completing the steps above, you will have an LLM web app running on Ubuntu 24.04 that can operate long term and is accessible only to you.