1. Introduction & use cases
Node.js is a JavaScript runtime built on Chrome's V8 engine that runs JavaScript outside the browser. Its event loop and non-blocking I/O let one process handle many network connections at once, which makes it a great fit for APIs, real-time apps and tooling.
Node.js ships with npm, the world's largest package registry. Use an LTS (Long-Term Support) version in production – even-numbered releases become LTS and receive security fixes for about 30 months.
Where it is used
- REST and GraphQL APIs (Express, NestJS)
- Real-time apps – chat, notifications, live dashboards (Socket.IO)
- Build tools and CLIs (Vite, ESLint, TypeScript itself)
- Serverless functions on AWS Lambda
2. Prerequisites
| You need | Version / notes |
|---|---|
| Operating system | Windows 10/11, macOS or Linux (64-bit) |
| nvm (recommended) | Node Version Manager – nvm-windows on Windows |
| Terminal | bash/zsh, PowerShell or Windows Terminal |
| Editor | VS Code |
3. Local setup
1Install nvm (macOS / Linux)
nvm lets you install several Node.js versions side by side. Check the nvm README for the latest install command.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash # reopen the terminal, then: nvm --version2Install Node.js LTS
On Windows install nvm-windows (or the installer from nodejs.org) and run the same commands in PowerShell.
BASHnvm install --lts nvm use --lts node -v npm -v3Pin the version for the project
A
.nvmrcfile lets everyone runnvm useand get the same version.BASHnode -v > .nvmrc nvm use
4. Create & run a project
1Create a project
npm init -ycreatespackage.json. Set"type": "module"to useimportsyntax.BASHmkdir hello-node && cd hello-node npm init -y npm pkg set type=module2Write an HTTP server
The built-in
node:httpmodule needs no packages. It returns JSON and reads the port from the environment.server.jsimport { createServer } from 'node:http'; const port = process.env.PORT || 3000; const server = createServer((req, res) => { if (req.url === '/health') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ status: 'ok' })); } res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Hello from Node.js!'); }); server.listen(port, () => console.log(`Server running at http://localhost:${port}`));3Add npm scripts
--watchrestarts on file changes;--env-fileloads.env(Node 20.6+).BASHnpm pkg set scripts.dev="node --watch --env-file=.env server.js" npm pkg set scripts.start="node server.js"4Run and test it
Start the server and call it from a second terminal (or open the URL in a browser).
BASHnpm run dev curl http://localhost:3000/health
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Read configuration from process.env. Node.js can load a .env file itself with --env-file=.env (no dotenv package needed on Node 20.6+). In production set variables in the process manager or systemd unit instead.
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/appKey dependencies
| Package / tool | Used for |
|---|---|
npm | Package manager (npm install, npm ci, scripts) |
node --watch | Built-in auto-restart (replaces nodemon for simple cases) |
express / fastify | Web frameworks for larger APIs |
pm2 | Process manager in production |
eslint, prettier | Linting and formatting |
Folder structure
hello-node/
├── src/ # application code
├── server.js # entry point
├── .env # local settings (git-ignored)
├── .env.example
├── .nvmrc # Node version
├── package.json
└── package-lock.json # exact dependency versionsEssential commands
| Command | What it does |
|---|---|
npm init -y | Create package.json |
npm install <pkg> | Add a dependency (-D for dev only) |
npm ci | Clean install from the lockfile (CI/servers) |
npm run dev | Run with auto-restart |
npm outdated / npm audit | Find old or vulnerable packages |
node --inspect server.js | Debug with Chrome DevTools |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu 24.04 VPS, 1 vCPU / 1 GB RAM for small APIs |
| Runtime | Same Node.js LTS major as development |
| Process manager | PM2 (or a systemd unit) |
| Reverse proxy | Nginx on 80/443 → app port |
| Domain + SSL | DNS A record + Let’s Encrypt |
Deployment steps
1Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP2Install Node.js on the server
Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/hello-node cd /var/www/hello-node npm ci --omit=dev4Set production environment variables
Create the env file on the server only (never in Git).
BASHcat > /var/www/hello-node/.env <<'EOF' NODE_ENV=production PORT=3000 EOF chmod 600 /var/www/hello-node/.env5Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo npm install -g pm2 pm2 start server.js --name hello-node --node-args="--env-file=.env" pm2 startup # run the command it prints pm2 save pm2 logs hello-node # live logs pm2 restart hello-node # after each deploy6Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }7Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx8Open only the ports you need
Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status9Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com10Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
Error: listen EADDRINUSE: address already in use :::3000
Another process uses the port. Stop it or change PORT. Find it with:
lsof -i :3000 # macOS/Linux
netstat -ano | findstr :3000 # WindowsSyntaxError: Cannot use import statement outside a module
Add "type": "module" to package.json or rename the file to .mjs (or use require() in CommonJS).
npm ERR! code EACCES when installing globally
Do not use sudo npm – install Node.js with nvm so global packages go into your home folder.
App stops when you close SSH
A plain node server.js dies with the session. Use PM2 or systemd.
502 Bad Gateway from Nginx
The app is not running or listens on a different port/host. Check pm2 logs and that proxy_pass matches the port.
JavaScript heap out of memory
Look for memory leaks first; temporarily raise the limit with node --max-old-space-size=1024.
Best practices
- Use an LTS version and pin it with
.nvmrcand theenginesfield. - Commit
package-lock.jsonand usenpm ciin CI and on servers. - Never commit
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store. - Handle
SIGTERMto close servers and database connections gracefully during deploys. - Run
npm auditregularly and keep dependencies updated.