DEV Community

Cover image for Mastering Web Development: Cookies, Authorization, Authentication, and File Uploads in Node.js
Sushant Gaurav
Sushant Gaurav

Posted on

Mastering Web Development: Cookies, Authorization, Authentication, and File Uploads in Node.js

In our previous articles, we've laid the foundation of NodeJS, exploring its core concepts, including how NodeJS works, building servers, managing URLs, HTTP methods, utilizing the power of the Express framework, REST APIs, middleware, HTTP headers, MongoDB, Models, Views, Controllers, differences between stateful and stateless systems, session management, authentication and authorization in NodeJS, JWT tokens, cookies, etc.

Link to the previous articles:

  1. Getting Started with NodeJS
  2. Deepening NodeJS Knowledge: URLs, HTTP Methods, Express Framework, and Versioning
  3. Mastering NodeJS: REST APIs, Middleware, and HTTP Headers
  4. Mastering Backend Development with NodeJS: MongoDB Integration, Mongoose, CRUD Operations, and MVC Architecture
  5. Securing Web Applications: Stateful vs. Stateless Systems, Authentication, and Authorization in Node.js

Continuing our journey into NodeJS, this article explores Cookies, Authorization, Authentication, and File Uploads in Node.js, focusing on how they work, why they are important, and how to implement them.

Understanding Cookies in JavaScript

What Are Cookies?

Cookies are small pieces of data stored on the user's browser. They are used to remember information about the user, like login status, user preferences, and session details. Cookies are sent from the server to the client and stored in the user's browser. On subsequent requests, the browser sends these cookies back to the server, helping the server recognize the user.

When and Why to Use Cookies?

  • Session Management: Keep users logged in by storing session IDs.
  • Personalization: Store user preferences, such as themes and languages.
  • Tracking: Monitor user behaviour on your site for analytics.

How to Use Cookies in JavaScript

You can easily create, read, and delete cookies using JavaScript. Here’s a basic example:

// Setting a cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/";

// Reading a cookie
const cookies = document.cookie;
console.log(cookies); // Outputs: username=JohnDoe

// Deleting a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Enter fullscreen mode Exit fullscreen mode

Use Case: Persistent Login

Imagine a user logging into your website. You can store their session ID in a cookie, so the next time they visit, they don’t need to log in again.

Authorization in JavaScript

What Is Authorization?

Authorization is the process of determining if a user has permission to perform a certain action. For example, only admins should be allowed to delete user accounts.

When and Why to Use Authorization?

  • Security: Ensure users can only access what they’re allowed to.
  • Role Management: Differentiate between user roles, like admins and regular users.

How to Implement Authorization in JavaScript

Authorization is often handled server-side, but the logic can be enforced client-side as well.

const userRole = "admin";

if (userRole === "admin") {
  console.log("Access granted: You can delete user accounts.");
} else {
  console.log("Access denied: You do not have permission to delete user accounts.");
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Role-Based Access Control (RBAC)

For a web application, you might have different roles like admin, editor, and viewer. Authorization logic will ensure that only users with the admin role can access sensitive functionalities like managing other users.

Authentication vs. Authorization: A Practical Use Case

Authentication

Authentication verifies a user's identity. This is usually done with a username and password, OAuth tokens, or biometrics.

Authorization

After authentication, the system checks what resources the authenticated user is allowed to access, i.e., it authorizes them.

Use Case: Securing a Dashboard

  • Step 1: User logs in (Authentication).
  • Step 2: Based on their role, they are given access to certain parts of the dashboard (Authorization).
// Authentication
function authenticate(username, password) {
  // Check username and password
  return username === "admin" && password === "password123";
}

// Authorization
function authorize(role) {
  if (role === "admin") {
    console.log("Access granted to the admin dashboard.");
  } else {
    console.log("Access denied.");
  }
}

// Usage
const isAuthenticated = authenticate("admin", "password123");
if (isAuthenticated) {
  authorize("admin");
}
Enter fullscreen mode Exit fullscreen mode

How to Upload Files in Node.js

The Need for File Uploads

Uploading files is a common feature in many web applications, allowing users to submit documents, images, or other files.

Setting Up File Uploads in Node.js

Node.js doesn’t handle file uploads by itself. Instead, we use a middleware called Multer. Multer makes handling multipart/form data easy, which is essential for uploading files.

Installing Multer

First, install Multer using npm:

npm install multer
Enter fullscreen mode Exit fullscreen mode

Configuring Multer for File Uploads

Here’s a basic setup for uploading files:

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

// Configure storage
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

// Initialize multer
const upload = multer({ storage: storage });

// Route to handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully!');
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Use Case: Profile Picture Upload

Imagine a user updating their profile picture. They upload an image file, and Multer saves it to the server, associating it with the user’s profile.

Multer: A Closer Look

What Is Multer?

Multer is a middleware for handling multipart/form-data, primarily used for file uploads.

Why Use Multer?

  • Ease of Use: Simplifies the process of handling file uploads in Node.js.
  • Customizable: Allows you to define storage locations and file naming conventions.
  • Secure: Provides options to filter and validate files before uploading.

Example: File Upload with Multer

Here’s how you can restrict the file types to images only:

const upload = multer({
  storage: storage,
  fileFilter: function (req, file, cb) {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Not an image! Please upload an image.'), false);
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Use Case: Handling User Profile Images

By using Multer, you can allow users to upload only images as their profile pictures. The middleware will automatically filter out non-image files, ensuring your application remains secure and user-friendly.

Conclusion

Understanding and implementing cookies, authorization, authentication, and file uploads in Node.js are fundamental skills for any web developer. By mastering these concepts, you’ll be able to build secure, efficient, and user-friendly applications. Whether you’re managing sessions with cookies, securing your app with authorization, or handling file uploads with Multer, these tools are essential in modern web development.

Top comments (0)