Express.js for Beginners

Express.js for Beginners

Basic Overview of Express JS

ยท

6 min read

Express.js is one of the most popular web application frameworks for Node.js. It's known for its simplicity and flexibility, it powers a wide range of applications, from small APIs to large-scale web services.

Index

  1. Setting Up an Express.js Application

  2. Routing in Express.js

  3. Middleware in Express.js

  4. Handling Requests and Responses

  5. Serving Static Files

  6. Template Engines and Rendering Views

  7. Authentication and Security

  8. Environment Variables and Configuration

  9. Working with Databases

  10. Best Practices and Common Patterns


1. Setting Up an Express.js Application

Getting started with Express.js is straightforward:

  • Install Node.js:
    Ensure that Node.js is installed on your machine.
    If not follow this link https://nodejs.org/en/download

  • Initialize a New Project:
    Run npm init -y to generate a package.json file.

  • Install Express.js:
    Use npm i express to add Express.js to your project.

    initialize app.js: create a file app.js/index.js and initialize the express app
    We have to store the instance of express in variable to perform required operations.
    In Node we use require to import the module learn more about if you are not aware Module System.

    Copy

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

2. Routing in Express.js

Routing refers to the process of selecting a path or route for data to travel across a network or communication system.
In Express.js, routing refers to the process of defining how an application responds to client requests for specific endpoints (URLs) and HTTP methods (like GET, POST, PUT, DELETE, etc.).

Express is a web framework for Node.js that simplifies the routing process, allowing you to set up routes for different parts of a web application. Routing is like the backbone of any Express.js application. Express provides a straightforward and intuitive way to define routes:

Basic Routing:

Handling GET, POST, PUT, and DELETE requests. Basically all HTTPS request handlers that you may have worked with. Check out this site to know about http request methods and its browsing compatibility developer.mozilla.org/en-US/docs/Web/HTTP/M..

Copy

//REQUEST HANDLERS 
app.get('/', (req, res) => {
    res.send("hello reader"); //prints on clientside
    console.log("HELLO READER"); //prints on serverside
}

Route Parameters:

In the route /users/:id, :id is a route parameter that can capture different user IDs from the URL. When a request is made to /users/123, Express will automatically capture 123 as the value of id. This dynamic value can then be accessed in the route handler using req.params.

Copy

Copy

//ROUTING PARAMETRS
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send("User ID: ${userId}");
});

Query Parameters:

Query parameters are appended to the URL after a question mark (?). Query parameters are separated by an ampersand (&) when multiple parameters are included. These parameters are accessible in the request handler via req.query.

Example:

Copy

///QUERY PARAMETERS
app.get('/search', (req, res) => {
  const searchTerm = req.query.term;
  const limit = req.query.limit;
  res.send(`Searching for "${searchTerm}" with a limit of ${limit} results.`);
});

3. Middleware in Express.js

Middleware functions execute during the lifecycle of a request to the server. When a request is made to the server, it passes through a stack of middleware functions in the order they are defined. See, middlewares are actually written callback functions in javascript that are passed to request handlers in terms of modifying the request object, sending the response, and passing the control (by invoking next(), OTHERWISE IT WILL BE LOADING FOREVER).

Middleware functions can modify the request or response, perform tasks like logging, authentication, data processing, and more, and decide whether to pass control to the next middleware function in the stack or send a response back to the client.

Middleware plays a central role in Express.js by allowing you to execute code at various points during the request handling process.Basically middleware are functions which get executed just before handling the request by client.

Copy

const logRequest = (req, res, next) => {
  console.log(`Request made to ${req.url}`);
  next();// Passing the control
};

// here logRequest is passed as middleware 
app.get('/', logRequest, (req, res) => {
  res.send('Home Page');
});

4. Handling Requests and Responses

Express makes it easy to handle HTTP requests and send responses:

  • Request Object: Access data sent by the client, including headers, query parameters, and the body.

  • Response Object: Send data back to the client using res.send(), res.json(), or res.render().

  • Chaining Methods: Use methods like res.status().json() to set the status code and send a JSON response.

    Copy

        app.get('/example', (req, res) => {
        res.status(200).json({ message: 'Success!' })
        }); //chaining status() and json() method
    

5. Serving Static Files

Express provides a simple way to serve static assets such as HTML, CSS, and JavaScript files that you don't want to render in every incoming request to reduce the workload of the server:

Copy

app.use(express.static('public')); 
//This single line of code allows you to serve files from the public directory.
๐Ÿ’ก
Remember your files in public directory are always accessible by clients

6. Template Engines and Rendering Views

Express integrates with various template engines like EJS (Embedded Javascript), Pug, and Handlebars to render dynamic HTML:

  • Setting Up a View Engine: Choose a template engine and configure it in Express. Its always better to start with ejs to get good approach.

  • Rendering Views: Use res.render() method to pass data to the view and generate dynamic content.

Example with EJS:

Copy

Copy

app.set('view engine', 'ejs');
app.get('/home', (req, res) => {
  res.render('home', { title: 'Home Page' });
});

7. Authentication and Security

Security is a critical aspect of web development. Express provides various tools and practices to secure your application:

  • Authentication: Implement JWT-based authentication or use third-party services like OAuth.

  • Security Middleware: Use helmet for setting HTTP headers, cors for cross-origin requests, and rate limiting to prevent DDoS attacks. Use libraries like bcrypt to hash and store passwords securely.

8. Environment Variables and Configuration

Manage sensitive data and configuration settings using environment variables:

  • dotenv: Use this package to load environment variables from a .env file.

  • Environment-Specific Configuration: Separate configurations for development, testing, and production.

Example:

Copy

Copy

require('dotenv').config();
const PORT = process.env.PORT || 3000;

9. Working with Databases

Express can connect to various databases, including MongoDB, MySQL, and PostgreSQL:

  • MongoDB: Commonly used with Mongoose ODM for managing MongoDB.

  • Relational Databases: Use libraries like Sequelize or TypeORM for interacting with SQL databases.

  • Database Connection: Set up and manage database connections within your Express application.

    "This section requires a separate, full-length article."

10. Best Practices and Common Patterns

To build scalable and maintainable Express applications, follow these best practices:

  • Modularize Your Code: Use express.Router to break down routes into smaller, manageable modules. Its always prefered to have a route folder in root directory to manage routers.

  • Use Async/Await: Handle asynchronous code gracefully to avoid callback hell like fetching data from an API and logging it using async/await.

  • Error handling: Use next(err) to pass errors to an error-handling middleware.

"If you like this article, don't forget to like and drop your opinion below ๐Ÿ‘‡"

ย