How do you prevent CSRF attacks?
Use sameSite cookies (sameSite: 'strict' or 'lax' prevents cross-site requests), CSRF tokens (random token in forms, verified server-side), and verify the Origin header matches your domain. sameSite cookies are the simplest and most effective.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Node.js Security Interview Questions Authentication, Injection, and Best Practices
Sign a JWT with user ID using jwt.sign(), store in an HTTP-only cookie (secure: true, sameSite: 'strict'), and verify on each request with auth middleware (jwt.verify). HTTP-only cookies prevent JavaScript access (XSS-safe). Never store JWTs in localStorage.
NoSQL injection occurs when user input like { $gt: '' } is passed directly to MongoDB queries, returning all documents. Prevent with express-mongo-sanitize (removes $ and . from req.body), validate input types, and use Mongoose schema validation.
Never store plain text. Use bcrypt: genSalt(10) for a random salt, hash(password, salt) for the hash, and compare(inputPassword, storedHash) for verification. bcrypt is deliberately slow (resists brute-force) and uses salts (prevents rainbow table attacks).
Still have questions?
Browse all our FAQs or reach out to our support team
