Request Processing
Cookie Parsing
Parse and manage cookies with support for signed cookies and secure cookie handling for authentication and preferences.
Basic Cookie Parsing
MoroJS provides built-in cookie parsing middleware with support for signed cookies and secure cookie handling.
Enable Cookie Parsingtypescript
1import { middleware } from '@morojs/moro';
2
3// Enable cookie parsing with signed cookies
4app.use(middleware.cookie({
5 secret: 'your-secret-key',
6 signed: true
7}));
8
9// Access cookies
10app.get('/api/preferences', (req, res) => {
11 const theme = req.cookies.theme; // Regular cookie
12 const user = req.signedCookies.user; // Signed cookie
13
14 return { theme, user };
15});
16
17// Set cookies
18app.post('/api/preferences', (req, res) => {
19 res.cookie('theme', req.body.theme, {
20 maxAge: 365 * 24 * 60 * 60 * 1000, // 1 year
21 httpOnly: true,
22 secure: process.env.NODE_ENV === 'production',
23 sameSite: 'strict'
24 });
25
26 // Set signed cookie
27 res.cookie('user', userData, {
28 signed: true,
29 httpOnly: true,
30 secure: true,
31 sameSite: 'strict'
32 });
33
34 return { success: true };
35});Cookie Features
- Automatic cookie parsing from requests
- Support for signed cookies
- Secure cookie flags (httpOnly, secure, sameSite)
- Cookie expiration management
- Cookie deletion support
Advanced Configuration
Advanced Cookie Configurationtypescript
1import { middleware } from '@morojs/moro';
2
3// Advanced cookie configuration
4app.use(middleware.cookie({
5 secret: process.env.COOKIE_SECRET,
6 signed: true,
7 keys: ['key1', 'key2'], // Multiple keys for key rotation
8 secure: process.env.NODE_ENV === 'production',
9 sameSite: 'strict'
10}));
11
12// Set cookie with all options
13res.cookie('session', sessionData, {
14 maxAge: 24 * 60 * 60 * 1000, // 24 hours
15 expires: new Date(Date.now() + 86400000), // Alternative to maxAge
16 httpOnly: true, // Not accessible via JavaScript
17 secure: true, // HTTPS only
18 sameSite: 'strict', // CSRF protection
19 domain: '.example.com', // Cookie domain
20 path: '/', // Cookie path
21 signed: true // Sign cookie value
22});
23
24// Delete cookie
25res.clearCookie('session', {
26 httpOnly: true,
27 secure: true,
28 sameSite: 'strict'
29});Best Practices
Do
- Use signed cookies for sensitive data
- Set httpOnly flag for security
- Use secure flag in production
- Set sameSite: 'strict' for CSRF protection
- Use strong cookie secrets
- Set appropriate expiration times
Don't
- Store sensitive data in unsigned cookies
- Skip httpOnly flag for sensitive cookies
- Use weak cookie secrets
- Set very long expiration times
- Store large objects in cookies
- Trust client-side cookie values