Tutorial
Backend & Middleware

Backend Configurations and Middleware Setup

📝 Code

Make a file named index.js in the server folder and add the following code to it.


GalaxyGossip
 ├── server
    ├── index.js
index.js
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";
import { fileURLToPath } from "url";
 
/* CONFIGURATIONS */
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use("/assets", express.static(path.join(__dirname, "public/assets")));
 
/* FILE STORAGE */
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/assets");
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});
const upload = multer({ storage });
 

✅ Explanation

Importing modules

  • express: Express is a popular Node.js web framework that provides a set of features for building web applications and APIs. It provides a simple and flexible API for handling HTTP requests and responses, routing, middleware, and more.
  • body-parser: Body-parser is a middleware that parses incoming request bodies in a middleware before your handlers, available under the req.body property. It supports parsing of JSON, URL-encoded, and multipart/form-data payloads.
  • mongoose: Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a simple and powerful API for defining schemas, validating data, querying the database, and more.
  • cors: CORS (Cross-Origin Resource Sharing) is a middleware that enables Cross-Origin Resource Sharing with various options. It allows clients from other domains or ports to access your server's resources.
  • dotenv: Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. This allows you to keep sensitive information like API keys and database credentials out of your codebase.
  • multer: Multer is a middleware that handles file uploads in forms. It provides a simple API for handling multipart/form-data requests and storing uploaded files.
  • helmet: Helmet is a middleware that helps secure your Express apps by setting various HTTP headers. This helps protect against common web vulnerabilities like cross-site scripting (XSS) and clickjacking attacks.
  • morgan: Morgan is a middleware that logs HTTP requests. It provides various logging formats including Apache combined log output format.

Configurations

  • __filename and __dirname: These variables are used to get the current filename and directory name of the current module file. They are used in conjunction with other modules like path to construct file paths relative to the current module file.
  • dotenv.config(): This loads environment variables from a .env file into process.env. This allows you to keep sensitive information out of your codebase and easily configure your app for different environments (e.g., development, production).
  • app.use(express.json()): This middleware parses incoming JSON payloads with a middleware before your handlers, available under the req.body property. This allows you to access the request body data in your route handlers using the req.body property.
  • app.use(helmet()): This middleware sets various HTTP headers to help secure your Express app against common web vulnerabilities like XSS and clickjacking attacks.
  • app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" })): This middleware sets the Cross-Origin Resource Policy (CORP) header to cross-origin to allow cross-origin access to resources.
  • app.use(morgan("common")): This middleware logs HTTP requests using the Apache combined log output format. This helps you debug your application and monitor traffic.
  • app.use(bodyParser.json({ limit: "30mb", extended: true })) and app.use(bodyParser.urlencoded({ limit: "30mb", extended: true })): These middlewares parse incoming request bodies with JSON or URL-encoded payloads respectively before passing them on to your route handlers. The limit option is used to limit the size of incoming payloads to 30MB, while the extended option allows parsing of URL-encoded data with rich objects and arrays support.
  • app.use(cors()): This middleware enables Cross-Origin Resource Sharing (CORS) for all routes in your Express app. This allows clients from other domains or ports to access your server's resources.

File storage

  • storage object: This object is used to configure where uploaded files should be stored. In this case, we specify that files should be stored in the public/assets directory with their original filenames.
  • upload object: This object is used to configure how uploaded files should be handled. In this case, we specify that files should be stored using the storage object defined above.

Here's an explanation of how each section of code works:

Importing modules

The first section of code imports several modules that are used throughout the application:

express

Express is a popular Node.js web framework that provides a set of features for building web applications and APIs. It provides a simple and flexible API for handling HTTP requests and responses, routing, middleware, and more.

body-parser

Body-parser is a middleware that parses incoming request bodies in a middleware before your handlers, available under the req.body property

Code Explanation

 
import express from "express"; // Importing express module
import bodyParser from "body-parser"; // Importing body-parser module
import mongoose from "mongoose"; // Importing mongoose module
import cors from "cors"; // Importing cors module
import dotenv from "dotenv"; // Importing dotenv module
import multer from "multer"; // Importing multer module
import helmet from "helmet"; // Importing helmet module
import morgan from "morgan"; // Importing morgan module
import path from "path"; // Importing path module
import { fileURLToPath } from "url"; // Importing fileURLToPath function
 
/* CONFIGURATIONS */
const __filename = fileURLToPath(import.meta.url); // Getting the current filename of the current module file using fileURLToPath function
const __dirname = path.dirname(__filename); // Getting the current directory name of the current module file using path.dirname function
dotenv.config(); // Loading environment variables from .env file into process.env
const app = express(); // Creating an instance of express
 
app.use(express.json()); // Parsing incoming JSON payloads with a middleware before your handlers, available under the req.body property
app.use(helmet()); // Setting various HTTP headers to help secure your Express app against common web vulnerabilities like XSS and clickjacking attacks
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" })); // Setting the Cross-Origin Resource Policy (CORP) header to cross-origin to allow cross-origin access to resources
app.use(morgan("common")); // Logging HTTP requests using the Apache combined log output format. This helps you debug your application and monitor traffic.
app.use(bodyParser.json({ limit: "30mb", extended: true })); // Parsing incoming request bodies with JSON payloads before passing them on to your route handlers. The limit option is used to limit the size of incoming payloads to 30MB, while the extended option allows parsing of URL-encoded data with rich objects and arrays support.
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true })); // Parsing incoming request bodies with URL-encoded payloads before passing them on to your route handlers. The limit option is used to limit the size of incoming payloads to 30MB, while the extended option allows parsing of URL-encoded data with rich objects and arrays support.
app.use(cors()); // Enabling Cross-Origin Resource Sharing (CORS) for all routes in your Express app. This allows clients from other domains or ports to access your server's resources.
app.use("/assets", express.static(path.join(__dirname, "public/assets"))); // Serving static files in Express using express.static middleware
 
/* FILE STORAGE */
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/assets"); // Configuring where uploaded files should be stored. In this case, we specify that files should be stored in the public/assets directory with their original filenames.
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname); // Configuring how uploaded files should be named. In this case, we specify that files should be stored using their original filenames.
  },
});
const upload = multer({ storage }); // Configuring how uploaded files should be handled. In this case, we specify that files should be stored using the storage object defined above.