- read

The Best Way To Write Your Express.js Server

Kal 84

The Best Way To Write Your Express.js Server

Kal
JavaScript in Plain English
5 min read6 days ago

--

Before we break down tips that add up to writing the best server, let’s discuss a bit about express.js.

Node.js has a core module known as ‘http’ to create an HTTP server and handle requests.

const http = require('http');

const server = http.createServer((req, res) => {
res.end('node.js is cool!');
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});

In this example, we imported the http module and created a server and the server takes a req and res parameters where a request is used to take input from a user and a response is used to send response data back to the user who sent a request to the server. The server listens on port 3000 and responds with “node.js is cool!” for every request. So when the user enters http://localhost:3000, “node.js is cool!!” is what they get a response.

So why not use the http module and what is the need for other frameworks? Frameworks like express.js are built on top of node.js to facilitate an easy and fast development process. It makes it easy to define route paths, and middleware and create structure. So the same code can be re-written in express.js like this:-

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('node.js is cool!');
});

const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
const httpServer = http.createServer(app);
const server = httpServer.listen(config.port, () => {
logger.info(`server listening on port ${config.port}`);
});

So as you can see express.js provides a simple way to define routes for your application. You just need to add `app.method_name` and as easy as that you can add routes.

There are multiple ways to create your express.js server, write your routes, and structure your functions. But these tips can help you build a better server and code structure.

1. Combine http module with express.js when you create your server

const http = require('http');
const express = require('express');
const app = express();


app.get('/', (req, res) => {
res.send('node.js is cool!');
});

const PORT = 3000;

const httpServer = http.createServer(app);

const server = httpServer.listen(PORT, () => {
console.log(`server listening on port ${PORT}`);
});

This is a fantastic way to create a server because

1.1) HTTPS Support

This can be easily extended to support HTTPS by importing the HTTP module. You can use the same server setup for both HTTP and HTTPS by providing the appropriate SSL/TLS certificates. This flexibility allows you to serve your application securely over HTTPS when needed.

const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

app.get('/', (req, res) => {
res.send('node.js is cool!');
});

// Paths to SSL certificate and private key
const privateKey = fs.readFileSync('key.pem', 'utf8');
const certificate = fs.readFileSync('cert.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate };

// Create an HTTPS server with Express
const PORT = 443; // Default HTTPS port
const httpsServer = https.createServer(credentials, app);

// Start the server and listen on the specified port
httpsServer.listen(PORT, () => {
console.log(`Server is running on HTTPS port ${PORT}`);
});

HTTPS is a secure version of HTTP and by using this method you can easily switch between the two protocols or have both of them on your server.

1.2) Have direct access to the http low-level events and other information

When you create the server using the http module, you can directly manipulate and handle low-level events and raw data associated with HTTP requests and responses. You gain access to low-level events and raw data, allowing for precise control over the server behavior.

This level of control can be valuable for specific use cases where you need to optimize performance or implement custom logic for example you could listen to the close event like this:-

server.on('close', () => {
// Perform cleanup operations
})

Or you could listen to the connection event to access the underlying socket, allowing you to perform custom actions related to the network connection.

server.on('connection', (socket) => {
// Handle the TCP socket connection
});

1.3) For routes that need a very high-performance

By handling certain routes directly with the http module, you can achieve lower latency and faster response times, especially for simple requests that don't require the full Express.js feature set.

2. Separate the routes

  • Organize your routes into separate modules. As your application grows, having all routes in a single file can become unmanageable. Use express.Router() to create modular, maintainable route handlers.
// routes/task.js
const express = require('express');
const router = express.Router();

router.get('/task', (req, res) => {
// return task here
});

module.exports = router;

If you would like to add other related functionalities like adding, updating, or deleting tasks you could do so by just adding on a single route.

// routes/task.js
const express = require('express');
const router = express.Router();

router('/task')
.get((req, res) => {
// return a task here
})
.post((req, res) => {
// create a task here
})
.put((req, res) => {
//update a task here
});

module.exports = router;

What is even better is to separate the functions into another file.

// controllers/task.js 
const getTask = (req, res) => {
// return task here
}
const createTask =(req, res) => {
// create task here
}
const updateTask =(req, res) => {
// update task here
}

module.exports = {getTask, createTask, updateTask};

And you can import it in routes/tasks.js as follows:-

// routes/task.js
const express = require('express');
const router = express.Router();
const {getTask, createTask, updateTask} = require('./controller/task.js')

router('/task')
.get(getTask)
.post(createTask)
.put(updateTask);

module.exports = router;

3. Add time out

Set appropriate timeouts for request and response handling to prevent your server from waiting indefinitely for slow requests.

you can simply do that by adding setTimeOut on the server

const http = require('http');
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('node.js is cool!');
});

const PORT = 3000;

const httpServer = http.createServer(app);

httpServer.setTimeout(5000); // Set timeout to 5 seconds (5000 milliseconds)

const server = httpServer.listen(PORT, () => {
console.log(`server listening on port ${PORT}`);
});

Click here to receive more tips, blogs, and courses for free! And sharpen your skill set and stand out. https://kalt.substack.com/

Thanks and Happy coding ✌️

In Plain English

Thank you for being a part of our community! Before you go: