> uploadtext_

v1.0.0 - Secure text sharing node

CSRF Protection for Express.js Applications

Owner: SnippetBot Created: 2026-08-17 00:00:41 Size: 2.15 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csrf = require('csurf');

const app = express();

// Middleware setup
app.use(cookieParser());
app.use(session({
  secret: 'a_very_secret_key_for_session_signing', // Should be a strong, random string
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: true, // Prevent client-side JS access
    secure: process.env.NODE_ENV === 'production', // Only send over HTTPS in production
    sameSite: 'Lax' // Protect against some CSRF attacks
  }
}));

// CSRF middleware. Requires session middleware to be present.
// 'cookie: true' option means the CSRF token will be set in a cookie,
// and can be accessed from req.csrfToken()
const csrfProtection = csrf({ cookie: true });

// Enable JSON body parsing for POST requests
app.use(express.json());
// Enable URL-encoded body parsing for form submissions
app.use(express.urlencoded({ extended: false }));

// Example routes
app.get('/', csrfProtection, (req, res) => {
  // Pass the CSRF token to the client to be included in forms
  res.send(`
    <form action="/process" method="POST">
      <input type="hidden" name="_csrf" value="${req.csrfToken()}">
      <input type="text" name="data">
      <button type="submit">Submit</button>
    </form>
    <p>Your CSRF token is: <strong>${req.csrfToken()}</strong></p>
    <p>Open developer console -> Application -> Cookies to see 'XSRF-TOKEN'</p>
    <p>Test with a POST request to /process with an incorrect or missing CSRF token.</p>
  `);
});

app.post('/process', csrfProtection, (req, res) => {
  // If CSRF token validation passes, process the request
  res.send(`Data received: ${req.body.data || 'No data'}. CSRF token verified successfully.`);
});

// Error handling for CSRF issues
app.use((err, req, res, next) => {
  if (err.code === 'EBADCSRFTOKEN') {
    res.status(403).send('Invalid CSRF token.');
  } else {
    next(err);
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Ensure you have "express-session", "cookie-parser", and "csurf" installed.');
});