Starting a Node.js Server
To start a Node.js server, initialize a project, write a small server script using the built-in http module or a framework like Express, and run it with node. From there you can open the app in a browser, add routing, and move toward a production setup. The steps below work on macOS, Linux, and Windows.
More from this site
Keep reading the latest coverage
Prerequisites
- Node.js installed (check with node -v)
- A code editor such as VS Code
- Basic familiarity with the terminal
Step-by-Step Setup
1. Initialize the project
Create a new folder, open it in your terminal, and run npm init -y. This creates a package.json file that tracks dependencies and scripts.
2. Create the server file
Make a file called server.js and paste the following minimal code:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello from Node.js\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });3. Run the server
In the terminal, execute node server.js. You should see the message Server running at http://127.0.0.1:3000/. Open that URL in a browser to confirm the server is responding.
4. Use a framework for real projects
For routing, middleware, and faster development, install Express with npm install express and replace the native http logic with a concise Express app. This keeps the startup flow the same while giving you more structure.
Stopping and Restarting
Press Ctrl + C in the terminal to stop the server. If you edit the code, restart it with node server.js. For faster iteration during development, consider nodemon, which restarts automatically on file changes.
Next Steps Toward Production
- Set the environment to production with NODE_ENV=production
- Use a process manager like PM2 to keep the server running
- Add a reverse proxy such as Nginx or Caddy
- Secure the app with HTTPS and environment-based configuration