How Authentication is done in MERN Stack ?

1. User Registration

To enable user account creation in your MERN application, implement an API endpoint dedicated to user registration. Upon signing up, the user’s password must undergo secure hashing before being stored in the database.

Javascript




// routes/auth.js
 
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
 
// Registration routes
router.post('/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;
    // Hash the password before saving it to the database
    const hashedPassword = await bcrypt.hash(password, 10);
    const user = new User({ username, email, password: hashedPassword });
    await user.save();
    res.status(201).json({ message: 'Registration successful' });
  } catch (error) {
    res.status(500).json({ error: 'Registration failed' });
  }
});


2. User Login

To implement a login endpoint that checks the user’s credentials and generates a JWT token upon successful login, you’ll need to follow a few steps. Below is an example of how you can do this within a MERN stack application:

First, ensure you have the necessary dependencies installed. You’ll need express, bcrypt for password hashing, and jsonwebtoken for generating JWT tokens.

Javascript




javascriptCopy code
// routes/auth.js
 
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key';
 
// Login endpoint
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ email });
 
    if (!user) {
      return res.status(401).json({ error: 'Authentication failed try Again' });
    }
 
    const passwordMatch = await bcrypt.compare(password, user.password);
 
    if (!passwordMatch) {
      return res.status(401).json({ error: 'Authentication failed try Again' });
    }
 
    // Create a JWT token
    const token = jwt.sign({ userId: user._id, email: user.email }, secretKey, {
      expiresIn: '1h',
    });
 
    res.status(200).json({ token, userId: user._id });
  } catch (error) {
    res.status(500).json({ error: 'Authentication failed try Again' });
  }
});


5 Simple Steps for Authentication and Authorization in MERN Stack

Implementing authentication and authorization in a MERN stack application is crucial for ensuring the security of your application and protecting sensitive data. Here’s an elaboration on the five simple steps you can take to achieve this:

Table of Content

  • Implementing Authentication and Authorization in MERN App:
  • How Authentication is done in MERN Stack ?
  • How Authorization is done in MERN Stack:
  • Steps to implement Authentication & Authorization in Backend:

Similar Reads

Implementing Authentication and Authorization in MERN App:

Import Statements: Import necessary dependencies and components. React is imported for defining React components. App.js is a custom component, assumed to be present in the Home directory. Import JWT to your node application. Define backend: Define requests to handled by backend(example login, logout,registration). Create your routes: Create database to store the username, password for authentication. Handle your backend by creating backend API....

How Authentication is done in MERN Stack ?

1. User Registration...

How Authorization is done in MERN Stack:

...

Steps to implement Authentication & Authorization in Backend:

...

Folder Structure:

1. Protecting Routes...

Steps to Create a Frontend Application:

...

Folder Structure:

...