Express JS Express Security and Authentication 2 — Questions and Answers
Question 1: How does the express-session middleware store session data by default?
- In-memory on the server (not suitable for production) (Correct answer)
- In a database automatically
- In a cookie on the client
- In the file system
Correct answer: In-memory on the server (not suitable for production)
The default MemoryStore is in-process memory storage, which doesn't scale and leaks memory — use a persistent store in production.
Question 2: What is the purpose of setting httpOnly: true on session cookies in Express?
- Prevents client-side JavaScript from accessing the cookie (Correct answer)
- Forces HTTPS for the cookie
- Limits the cookie to the same origin
- Expires the cookie after one request
Correct answer: Prevents client-side JavaScript from accessing the cookie
The httpOnly flag prevents XSS attacks from stealing the session cookie via document.cookie in the browser.
Question 3: What does enabling 'trust proxy' in Express do for security?
- Tells Express to trust the X-Forwarded-For and other proxy headers for correct IP/protocol detection (Correct answer)
- Enables built-in SSL termination
- Trusts all incoming requests
- Disables authentication checks
Correct answer: Tells Express to trust the X-Forwarded-For and other proxy headers for correct IP/protocol detection
app.set('trust proxy', true) lets Express read X-Forwarded-For headers from a trusted reverse proxy for accurate req.ip.
Question 4: Which package is commonly used to implement Passport.js-based authentication in Express?
- passport (Correct answer)
- express-auth
- auth-middleware
- express-passport
Correct answer: passport
passport is the widely-used authentication middleware for Express that supports hundreds of strategies including local, OAuth, and JWT.
Question 5: What is the role of CORS in an Express API security context?
- Controls which origins are allowed to make cross-origin requests to the API (Correct answer)
- Encrypts API traffic
- Validates API keys
- Prevents SQL injection
Correct answer: Controls which origins are allowed to make cross-origin requests to the API
CORS headers restrict which web origins can call your API, preventing unauthorized cross-origin JavaScript from making API requests.
Question 6: What is SQL injection and how do you prevent it in an Express app using a database?
- Malicious SQL in inputs; prevent by using parameterized queries or an ORM (Correct answer)
- A type of CSRF attack
- Injecting SQL via HTTP headers only
- A server misconfiguration issue
Correct answer: Malicious SQL in inputs; prevent by using parameterized queries or an ORM
SQL injection occurs when untrusted input is concatenated into SQL strings; parameterized queries or ORMs prevent it by separating data from code.
How does the express-session middleware store session data by default?