EthicsComputerCourses
Join training +91 90532 10052

Deploying a MEVN App

MEVN Stack · Lesson 17 of 20 Intermediate 12 min read Updated

By the end of this lesson you will know how to put NoteNest on the internet at https://notenest.example. The Vue app is built into static files, Express serves both those files and the API from one process, systemd keeps that process running, Nginx adds HTTPS in front, and MongoDB runs with a least-privilege user. Everything stays on one site, so the SameSite=Strict login cookie keeps working.

What you should know first: Security Checklist for MEVN, whose TRUST_PROXY setting matters here, and the build step from Vue 3 Front End with Vite. Server basics are taught in Nginx as a Reverse Proxy for Node.js, HTTPS with Let's Encrypt & Certbot and systemd Services. Versions checked: Node.js 26 LTS, Express 5.3.0, Vite 8.3.8, Nginx 1.28.3 and MongoDB 9.0. The Nginx configs below passed nginx -t and served real traffic in our test run; the systemd and Ubuntu commands are written from the official documentation, because our test machine was not running Ubuntu.

The plan: one server, one origin

Think of a sweet shop in Lucknow with one front door. Customers never walk into the kitchen; the counter staff fetch everything. Nginx is the front door and the guard, Express is the counter, and MongoDB is the store room.

Text
Browser ──HTTPS──> Nginx :443 ──HTTP──> Express on 127.0.0.1:3000 ──> MongoDB on 127.0.0.1:27017
                   (TLS, body size)      /api/*   -> JSON routes
                                         /assets/* -> built Vue files
                                         anything else -> index.html

Why one origin? The app and the API share https://notenest.example, so the browser makes no cross-origin calls. The Strict cookie is always sent, Helmet's Cross-Origin-Resource-Policy: same-origin never blocks note images, and CORS has nothing to allow. Splitting them across hosts is possible, but every earlier lesson's warnings would then apply.

Step 1: Build the client

VITE_API_URL is not set in production, so apiRequest uses its default, /api, the same path on the same origin. Inside client/:

Terminal
npm run build
Output
vite v8.3.8 building client environment for production...
transforming...
✓ 39 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                            0.43 kB │ gzip:  0.28 kB
dist/assets/NoteDetailView-Dr5PxXAj.css    0.10 kB │ gzip:  0.11 kB
dist/assets/index-DJ1cdzvD.css             0.52 kB │ gzip:  0.30 kB
dist/assets/NotFoundView-oG5rtRNN.js       0.45 kB │ gzip:  0.33 kB
dist/assets/SignupView-BP9offm5.js         2.05 kB │ gzip:  1.03 kB
dist/assets/LoginView-CYoNFXNr.js          2.12 kB │ gzip:  1.06 kB
dist/assets/NoteDetailView-BICovVY7.js     3.14 kB │ gzip:  1.57 kB
dist/assets/index-C17tQAHF.js            107.33 kB │ gzip: 41.65 kB

✓ built in 840ms

That folder is the whole front end: no Node.js is needed to run it, only something to send the files.

Step 2: Serve dist/ from Express

Create server/src/spa.js. It answers three kinds of request differently:

JavaScript
// server/src/spa.js
import path from 'node:path'
import express from 'express'

// Serves the built Vue app from distDir, with a fallback for client-side routes.
export function serveClient(app, distDir) {
  // Hashed files never change, so browsers may keep them for a year.
  app.use('/assets', express.static(path.join(distDir, 'assets'), { immutable: true, maxAge: '1y' }))
  // Other files in dist/ (favicon.ico) for one hour; index.html is handled below.
  app.use(express.static(distDir, { index: false, maxAge: '1h' }))

  // Any other GET that is not an API call or an asset gets index.html,
  // so Vue Router can show /notes/:id, /login or its own 404 page.
  app.get('/{*path}', (req, res, next) => {
    if (/^\/(api|assets)(\/|$)/.test(req.path)) return next()
    res.sendFile('index.html', { root: distDir, headers: { 'Cache-Control': 'no-cache' } })
  })
}

'/{*path}' is Express 5's wildcard syntax; the Express 4 form '*' now throws an error at start-up. In config.js add clientDist: process.env.CLIENT_DIST ? path.resolve(process.env.CLIENT_DIST) : null, and in app.js, after the API routes and before notFound:

JavaScript
// In production the same server sends the built Vue app (same origin as the API).
if (config.clientDist) serveClient(app, config.clientDist)

In development CLIENT_DIST is unset and Vite serves the client as before. We started the server with NODE_ENV=production CLIENT_DIST=../client/dist and asked for five paths (status, type, cache header):

Output
/notes/6afaf61736245a9da24707f7      200 | text/html; charset=utf-8 | no-cache
/api                                 404 | application/json; charset=utf-8 |
/api/nope                            404 | application/json; charset=utf-8 |
/assets/index-C17tQAHF.js            200 | text/javascript; charset=utf-8 | public, max-age=31536000, immutable
/assets/index-OLD12345.js            404 | application/json; charset=utf-8 |

This is the promise from Routing with Vue Router kept: a refreshed note page gets index.html, while API typos keep their JSON 404. no-cache makes browsers check index.html on every visit, so they find new hashed file names right after a deploy. A missing old asset gets a real 404, not index.html pretending to be JavaScript.

Step 3: Production settings

On the server, settings live in one file outside the code folder, /etc/notenest/notenest.env, readable only by root. systemd reads it and passes the values to Node.js, which is why the start script never used --env-file:

Text
NODE_ENV=production
PORT=3000
HOST=127.0.0.1
TRUST_PROXY=loopback
CLIENT_ORIGIN=https://notenest.example
CLIENT_DIST=/srv/notenest/app/client/dist
UPLOAD_DIR=/var/lib/notenest/uploads
MONGODB_URI=mongodb://notenest-app:paste-the-app-password-here@127.0.0.1:27017/notenest
JWT_SECRET=paste-64-new-random-hex-characters-here

Three new settings deserve a word. HOST=127.0.0.1 makes Express listen only on the server itself; add host: process.env.HOST to config.js and pass it to app.listen(config.port, config.host, ...). From another computer on our network, a request straight to the Node port failed with curl error 7 (could not connect), so nobody can skip Nginx. TRUST_PROXY=loopback is the security lesson's setting. UPLOAD_DIR points outside the code, so a redeploy never deletes images.

Terminal
sudo mkdir -p /etc/notenest
sudo nano /etc/notenest/notenest.env
sudo chmod 600 /etc/notenest/notenest.env
node -p "crypto.randomBytes(32).toString('hex')"

Generate a fresh JWT_SECRET with the last command; never copy the development one.

Step 4: Stop gracefully

systemd stops or restarts a service by sending SIGTERM, a polite "please exit" signal. Let requests that are already running finish first. Update server/src/server.js:

JavaScript
// server/src/server.js
import mongoose from 'mongoose'
import app from './app.js'
import { config } from './config.js'
import { connectDB } from './db.js'

await connectDB(config.mongodbUri)

const server = app.listen(config.port, config.host, (error) => {
  if (error) throw error
  console.log(`NoteNest API listening on http://${config.host ?? 'localhost'}:${config.port}`)
})

// systemd and PM2 send SIGTERM on stop or restart: finish open requests, then exit.
process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing the server')
  server.close(async () => {
    await mongoose.disconnect()
    console.log('Closed cleanly')
    process.exit(0)
  })
})

We raised the signal inside a running server (process.emit('SIGTERM'), because our test machine was Windows):

Output
MongoDB connected: notenest on 127.0.0.1
NoteNest API listening on http://127.0.0.1:3147
SIGTERM received, closing the server
Closed cleanly

Step 5: The database

You have two good choices. Prices change, so check each provider's pricing page rather than any figure in a tutorial.

  • MongoDB Atlas (hosted). Create a database user with the readWrite role on notenest only, add only your server's public address to the IP access list (for example 203.0.113.10), and paste the mongodb+srv:// string into MONGODB_URI. Atlas handles backups and upgrades. See MongoDB Atlas Overview.
  • Self-hosted MongoDB 9.0 on the same server. In /etc/mongod.conf, keep net.bindIp: 127.0.0.1 and set security.authorization: enabled, then create an admin user and an app user.

We tested the self-hosted rules with a real MongoDB 9.0.2 started with --auth. The app user notenest-app got readWrite on notenest only. Then we connected as that user, inserted a note, and tried to read the admin database's user list:

Output
insert into notenest.notes: ok
MongoServerError: not authorized on admin to execute command { find: "system.users", filter: {}, limit: 1, singleBatch: true, lsid: { id: UUID("54c14310-e57c-4338-8d85-5ade550ee1fe") }, $db: "admin" }

With a wrong password the connection failed with MongoServerError: Authentication failed. So a bug or a leak in NoteNest exposes NoteNest's data and nothing else. Schedule backups with mongodump and copy them off the server; Backup & Restore shows how, and how to test a restore.

Step 6: Put the code on the server

Run the app as its own user with no login shell, so a break-in through Node.js cannot touch the rest of the system:

Terminal
sudo adduser --system --group --home /srv/notenest notenest
sudo -u notenest git clone https://github.com/your-name/notenest.git /srv/notenest/app
cd /srv/notenest/app/server && sudo -u notenest npm ci --omit=dev
cd /srv/notenest/app/client && sudo -u notenest npm ci && sudo -u notenest npm run build

Ubuntu 26.04's own nodejs package is the older 22 line, so install Node.js 26 LTS from the official nodejs.org downloads. --omit=dev skips supertest, mongodb-memory-server and other test tools on the server. Our run of the same command in a clean folder:

Output
added 125 packages, and audited 126 packages in 28s

37 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Step 7: Keep it running with systemd

A process manager starts the app at boot, restarts it after a crash (as promised in Error Handling & Middleware) and collects its logs. Create /etc/systemd/system/notenest.service:

Text
[Unit]
Description=NoteNest (Express API and Vue app)
After=network-online.target
Wants=network-online.target

[Service]
User=notenest
Group=notenest
WorkingDirectory=/srv/notenest/app/server
EnvironmentFile=/etc/notenest/notenest.env
ExecStart=/usr/bin/node src/server.js
Restart=on-failure
RestartSec=5
StateDirectory=notenest
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

StateDirectory=notenest creates /var/lib/notenest owned by the service user, the one folder the app may write to, because ProtectSystem=strict makes the rest of the disk read-only for it. Check the real path of Node.js with which node and adjust ExecStart. Then:

Terminal
sudo systemctl daemon-reload
sudo systemctl enable --now notenest
journalctl -u notenest -f

The journal should show the same two start-up lines you saw locally. If you prefer PM2, Deployment: PM2, Proxies & Docker covers it. Keep one instance: NoteNest's rate limiters count in memory, so several instances would each keep their own counters unless you move them to a shared store such as Redis.

Step 8: Nginx and HTTPS

Get a certificate with Certbot as in HTTPS with Let's Encrypt & Certbot, then create /etc/nginx/sites-available/notenest.conf:

Text
upstream notenest_app {
    server 127.0.0.1:3000;
    keepalive 8;
}

server {
    listen 80;
    listen [::]:80;
    server_name notenest.example;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name notenest.example;

    ssl_certificate     /etc/letsencrypt/live/notenest.example/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/notenest.example/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Images may be 2 MB; the multipart form adds a little on top.
    client_max_body_size 3m;

    location / {
        proxy_pass http://notenest_app;
        include proxy_params;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

proxy_params sends the real visitor address in X-Forwarded-For, which TRUST_PROXY=loopback reads. There is no HSTS line here because Helmet already sends Strict-Transport-Security; one place is enough.

The client_max_body_size line came from a real failure. Without it, Nginx's default of 1 MB applies, and our 1.4 MB whiteboard photo never reached multer:

Output
HTTP/1.1 413 Request Entity Too Large
Server: nginx
Content-Type: text/html

<html>
<head><title>413 Request Entity Too Large</title></head>

That is an HTML page, so the Vue client showed only "Request failed with status 413". With 3m, the same upload returned the usual {"note":{...}}, and Express's own 2 MB rule answers bigger files in the JSON shape. Enable the site, test and reload:

Terminal
sudo ln -s /etc/nginx/sites-available/notenest.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
curl -I https://notenest.example/notes/6afaf61736245a9da24707f7
Output
HTTP/1.1 200 OK
Server: nginx
Content-Type: text/html; charset=utf-8
Strict-Transport-Security: max-age=31536000; includeSubDomains
Cache-Control: no-cache

In headless Chrome we then opened a note link while logged out, landed on /login, logged in as Priya and returned to the note, with document.cookie empty (the cookie is HttpOnly) and no CSP errors in the console.

Step 9: Updating

Each release repeats four commands: git pull, npm ci --omit=dev in server/, npm ci && npm run build in client/, and sudo systemctl restart notenest. Run npm test on your machine or in CI before you pull on the server. The restart takes a few seconds, during which Nginx answers 502; for zero downtime see Zero-Downtime Deploys.

Check the routing rules

Type a path to see which rule in spa.js answers it.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Who answers this path?</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-width: 36rem; }
    input { width: 100%; padding: 4px; }
    li { margin-bottom: 4px; }
  </style>
</head>
<body>
  <h1>Who answers this path?</h1>
  <label for="path">Path</label>
  <input id="path" value="/notes/6afaf61736245a9da24707f7">
  <p id="answer"></p>
  <ul>
    <li>Try: <code>/api/notes</code>, <code>/api</code>, <code>/assets/index-C17tQAHF.js</code>, <code>/assets/old.js</code>, <code>/favicon.ico</code>, <code>/login?redirect=/</code></li>
  </ul>
  <script>
    const files = ["/favicon.ico", "/assets/index-C17tQAHF.js", "/assets/index-DJ1cdzvD.css"];
    const apiRoutes = [/^\/api\/health$/, /^\/api\/auth\/(login|signup|logout|me)$/, /^\/api\/notes(\/[^/]+(\/image)?)?$/];
    function answer(raw) {
      const path = new URL(raw, "https://notenest.example").pathname;
      if (apiRoutes.some((r) => r.test(path))) return "API route: JSON from Express (login needed for /api/notes)";
      if (files.includes(path)) {
        return path.startsWith("/assets/") ? "Static file, cached for 1 year (immutable)" : "Static file, cached for 1 hour";
      }
      if (/^\/(api|assets)(\/|$)/.test(path)) return "404 JSON: { error: { code: NOT_FOUND } }";
      return "index.html (no-cache), then Vue Router decides";
    }
    const input = document.querySelector("#path");
    const show = () => { document.querySelector("#answer").textContent = answer(input.value); };
    input.addEventListener("input", show);
    show();
  </script>
</body>
</html>

Common mistakes

  • Express listening on all addresses. Port 3000 is then open to the internet, skipping Nginx's HTTPS and limits. Set HOST=127.0.0.1 and a firewall (Firewalls: ufw & firewalld).
  • Forgetting client_max_body_size. Uploads over 1 MB fail with an HTML 413 from Nginx.
  • Uploads inside the code folder. A fresh clone or git clean deletes every image. Use /var/lib/notenest/uploads and back it up.
  • A .env file with real secrets inside the Git checkout. Keep it in /etc/notenest/, mode 600.
  • Caching index.html for a long time. Users keep old file names and see a broken app after a deploy. Only /assets/ gets the one-year cache.

Interview questions

1. Why does a single-page app need a fallback route on the server?

Vue Router handles paths like /notes/42 in the browser, but a refresh or a shared link asks the server for that path. The server must answer with index.html for page paths so the app can start and route itself, while API and asset paths must keep their real 404s.

2. Why serve the Vue build and the API from the same origin?

Same-origin requests need no CORS, cookies with SameSite=Strict are always sent, and resource policies such as Cross-Origin-Resource-Policy: same-origin do not block images. It also means one certificate and one domain to manage.

3. What does a process manager such as systemd or PM2 do for a Node.js app?

It starts the app at boot, restarts it after crashes, stops it gracefully with a signal, and collects its logs. systemd can also inject environment variables from a protected file and sandbox the process with options such as ProtectSystem and NoNewPrivileges.

4. How should a production MongoDB be exposed to the app?

Only over a private path: bound to localhost or a private network, or with an IP access list on Atlas, with authentication enabled. The app uses a user that has readWrite on its own database only, never an admin account.

Key points

  • npm run build turns the Vue app into dist/; Express serves it with serveClient, giving index.html to page paths and JSON 404s to /api and /assets.
  • Hashed assets get max-age=1y, immutable; index.html gets no-cache.
  • Production settings live in /etc/notenest/notenest.env (mode 600): NODE_ENV, HOST=127.0.0.1, TRUST_PROXY=loopback, CLIENT_DIST, UPLOAD_DIR, MONGODB_URI, JWT_SECRET.
  • systemd runs the app as an unprivileged user, restarts it on failure and sends SIGTERM, which server.js handles gracefully.
  • Nginx terminates HTTPS, forwards the real IP and needs client_max_body_size 3m for 2 MB images.
  • MongoDB listens privately with authentication; the app user has readWrite on notenest only, and backups leave the server.

Exercise

Rohan wants a quick health check that his monitoring service can call every minute at https://notenest.example/api/health, reporting whether MongoDB is connected. Change the route so it returns 200 {"status":"ok","db":"up"} when mongoose.connection.readyState is 1, and 503 {"status":"degraded","db":"down"} otherwise. Then explain why this route should not be covered by the 300-per-minute API limiter's counting in the same way as normal users, and how you would exclude it.

Show solution
JavaScript
// server/src/app.js
app.get('/api/health', (req, res) => {
  const up = mongoose.connection.readyState === 1 // 1 means connected
  res.status(up ? 200 : 503).json({ status: up ? 'ok' : 'degraded', db: up ? 'up' : 'down' })
})

A 503 tells the monitor that the app is alive but cannot serve data, which is different from Nginx's 502 when Node.js is down. One request a minute will never reach 300, but a busy monitor that shares an IP with real users would use up their allowance. Move the health route above app.use('/api', apiLimiter), or give the limiter skip: (req) => req.path === '/health' (inside the /api mount the path is relative). Keep the response tiny: never include version numbers or connection strings.

Quick Quiz

1. A user refreshes https://notenest.example/notes/42 and sees NoteNest's note page. Which part of the server made that work?

2. Why is HOST=127.0.0.1 set in production?

3. A 1.4 MB image upload fails with an HTML 413 page from Nginx. What fixes it?

4. Why does index.html get Cache-Control: no-cache while /assets files get a one-year cache?

Learn MEVN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call