MERN Stack Security Blueprint

To secure a MERN Stack application, add helmet for security headers and express-mongo-sanitize to block NoSQL injection. Put real JWT middleware in front of your routes, validate input with mongoose schemas, and lock CORS to specific origins. And always take user IDs from the auth middleware, never from the request body. This blueprint covers Express security middleware with MongoDB protection.

TL;DR

The MERN risks that matter most are NoSQL injection, Express middleware gaps, and sloppy JWT handling. Use mongoose with schema validation, sanitize every input, set CORS properly and store JWTs securely. Never trust a user ID the client sends you.

Express Security Middleware Express

Order matters here: these run on every request before your routes see it.

server/app.js
import express from 'express'
import helmet from 'helmet'
import cors from 'cors'
import rateLimit from 'express-rate-limit'
import mongoSanitize from 'express-mongo-sanitize'

const app = express()

// Security headers
app.use(helmet())

// CORS configuration
app.use(cors({
  origin: process.env.CLIENT_URL,
  credentials: true,
}))

// Rate limiting
app.use(rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
}))

// Prevent NoSQL injection
app.use(mongoSanitize())

app.use(express.json({ limit: '10kb' }))

JWT Authentication Middleware Node.js

server/middleware/auth.js
import jwt from 'jsonwebtoken'

export const protect = async (req, res, next) => {
  const token = req.cookies.token || req.headers.authorization?.split(' ')[1]

  if (!token) {
    return res.status(401).json({ error: 'Not authorized' })
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    req.user = await User.findById(decoded.id).select('-password')

    if (!req.user) {
      return res.status(401).json({ error: 'User not found' })
    }

    next()
  } catch (error) {
    return res.status(401).json({ error: 'Invalid token' })
  }
}

Mongoose Schema Validation MongoDB

server/models/Post.js
import mongoose from 'mongoose'

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Title is required'],
    maxlength: [200, 'Title cannot exceed 200 characters'],
    trim: true,
  },
  content: {
    type: String,
    required: true,
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
}, { timestamps: true })

export default mongoose.model('Post', postSchema)

Protected Route Example Express

Note where author comes from. It's req.user, set by the middleware above, not anything in the request body.

server/routes/posts.js
import express from 'express'
import { protect } from '../middleware/auth.js'
import Post from '../models/Post.js'

const router = express.Router()

router.post('/', protect, async (req, res) => {
  const { title, content } = req.body

  const post = await Post.create({
    title,
    content,
    author: req.user._id,  // Use verified user from middleware
  })

  res.status(201).json(post)
})

router.get('/mine', protect, async (req, res) => {
  const posts = await Post.find({ author: req.user._id })
  res.json(posts)
})

Never trust client IDs. Use req.user from your auth middleware. Not req.body.userId, not anything else the client controls.

Security Checklist

Pre-Launch Checklist

Alternative Stacks

Not set on React? The closest alternatives:

Check Your MERN Stack App

Scan for injection and auth issues.

Security Blueprints

MERN Stack Security Blueprint