Here are six ways to create a web server in Node.js:
- Using HTTP Module
- Using Express
- Using Koa
- Using Hapi
- Using Fastify
- Using Restify
Method 1: Using HTTP Module
The simple way to create a Node.js server using the core http module. The HTTP module is part of the Node.js core, meaning you don’t need to install additional packages to use it.
To create a web server using Node.js, first, you need to install Node.js on your machine and then use http.createServer() method.
Create a file called “server.js” and add the below code in it:
// Load HTTP module const http = require('http'); // Define hostname and port const hostname = '127.0.0.1'; const port = 3000; // Create HTTP server and listen on the specified port const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('AI Overviews!\n'); }); // Start the server server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Save the file, go to the CMD or terminal, and type the following command to boot up the server:
node server
If you go to the browser and navigate to http://localhost:3000, you will see this page.
Method 2: Using Express
Express is a web framework for Node.js that simplifies creating web servers and adds helpful features such as validation, session, and middleware.
First, you need to install Express.
npm install express
Now, you can use the express module to create a web server.
Create a new file called “app.js” and add the below code:
// Load Express module const express = require("express"); // Create an instance of Express const app = express(); // Define the port const port = 4000; // Define a route handler for the root path app.get("/", (req, res) => { res.send("Hello, World!"); }); // Start the server app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Go to the terminal and type this command: node app
Method 3: Using Koa
Koa is a lightweight framework for Node.js that provides a more modern and modular approach to building web servers.
You need to install the Koa framework using the below command:
npm install koa
Create a new file called “data.js” and add the below code in it:
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Booting up server using Koa!'; }); app.listen(4000, () => { console.log('Server running at http://localhost:4000/'); });
Start the server using this command: node data
Method 4: Using Hapi
Hapi is a rich framework for building applications and services.
You can install the Hapi framework using the below command:
npm install @hapi/hapi
Create a new file called “main.js” and add the below code:
const Hapi = require("@hapi/hapi"); const init = async () => { const server = Hapi.server({ port: 3000, host: "localhost", }); server.route({ method: "GET", path: "/", handler: (request, h) => { return "We are the world!"; }, }); await server.start(); console.log("Server running at:", server.info.uri); }; init();
Save this file and boot up the development server using this command:
node main
Method 5: Using Fastify
Fastify web framework is designed for high performance and provides a flexible and modular structure.
Here is the command to install the Fastify framework:
npm install fastify
Create a new file called “boot.js” and add the below code:
const fastify = require('fastify')({ logger: true }); fastify.get('/', async (request, reply) => { return { msg: 'Hello, World!' }; }); const start = async () => { try { await fastify.listen({ port: 3000, host: '127.0.0.1' }); console.log('Server running at http://localhost:3000/'); } catch (err) { fastify.log.error(err); process.exit(1); } }; start();
Output
Method 6: Using Restify
Restify is a framework specifically designed for building RESTful web services.
const restify = require('restify'); const HttpParser = require('http-parser-js').HTTPParser; // Override Node.js's HTTP parser require('http').HTTPParser = HttpParser; // Create the server const server = restify.createServer(); // Middleware server.use(restify.plugins.bodyParser()); server.use(restify.plugins.queryParser()); // Define a simple route server.get('/', (req, res, next) => { res.send('From restify!'); next(); }); // Start the server server.listen(9000, () => { console.log('Server running at http://localhost:9000/'); });
Output
That’s all!