0
# Agent & Session Management
1
2
Agent-based session management with cookie persistence, connection pooling, and default request configuration for maintaining state across multiple requests.
3
4
## Capabilities
5
6
### Agent Creation
7
8
Create and configure agents for session management.
9
10
```javascript { .api }
11
/**
12
* Create a new agent with optional configuration
13
* @param {object} [options] - Agent configuration options
14
* @param {Buffer|string} [options.ca] - Certificate authority
15
* @param {Buffer|string} [options.key] - Client key
16
* @param {Buffer|string} [options.cert] - Client certificate
17
* @param {Buffer|string|object} [options.pfx] - PFX certificate
18
* @param {boolean} [options.rejectUnauthorized] - Whether to validate certificates
19
* @returns {Agent} New agent instance
20
*/
21
function agent(options?): Agent;
22
23
/**
24
* Agent constructor
25
* @param {object} [options] - Agent configuration options
26
*/
27
class Agent {
28
constructor(options?);
29
}
30
```
31
32
**Usage Examples:**
33
34
```javascript
35
const superagent = require('superagent');
36
37
// Basic agent creation
38
const agent = superagent.agent();
39
40
// Agent with TLS configuration
41
const httpsAgent = superagent.agent({
42
ca: fs.readFileSync('ca-cert.pem'),
43
key: fs.readFileSync('client-key.pem'),
44
cert: fs.readFileSync('client-cert.pem')
45
});
46
47
// Agent with certificate validation disabled (not recommended for production)
48
const insecureAgent = superagent.agent({
49
rejectUnauthorized: false
50
});
51
```
52
53
### Agent HTTP Methods
54
55
All standard HTTP methods are available on agent instances with the same signatures as the main superagent functions.
56
57
```javascript { .api }
58
/**
59
* Agent HTTP methods - same as superagent methods but with persistent session
60
*/
61
Agent.prototype.get(url, data?, callback?): Request;
62
Agent.prototype.post(url, data?, callback?): Request;
63
Agent.prototype.put(url, data?, callback?): Request;
64
Agent.prototype.patch(url, data?, callback?): Request;
65
Agent.prototype.delete(url, data?, callback?): Request;
66
Agent.prototype.del(url, data?, callback?): Request;
67
Agent.prototype.head(url, data?, callback?): Request;
68
Agent.prototype.options(url, data?, callback?): Request;
69
```
70
71
**Usage Examples:**
72
73
```javascript
74
const agent = superagent.agent();
75
76
// Login and get session cookie
77
await agent
78
.post('https://api.example.com/login')
79
.send({ username: 'user', password: 'pass' });
80
81
// Subsequent requests automatically include session cookies
82
const profile = await agent.get('https://api.example.com/profile');
83
const settings = await agent.get('https://api.example.com/settings');
84
85
// Update data with persistent session
86
await agent
87
.put('https://api.example.com/profile')
88
.send({ name: 'Updated Name' });
89
```
90
91
### Cookie Management
92
93
Automatic cookie persistence and management across requests.
94
95
```javascript { .api }
96
/**
97
* Agent cookie jar for session persistence
98
*/
99
Agent.prototype.jar: CookieJar;
100
101
/**
102
* Save cookies from response to agent's cookie jar
103
* @param {Response} res - Response object containing cookies
104
* @returns {Agent} Agent instance for chaining
105
*/
106
Agent.prototype.saveCookies(res): Agent;
107
108
/**
109
* Attach stored cookies to request
110
* @param {Request} req - Request object to attach cookies to
111
* @returns {Agent} Agent instance for chaining
112
*/
113
Agent.prototype.attachCookies(req): Agent;
114
```
115
116
**Usage Examples:**
117
118
```javascript
119
const agent = superagent.agent();
120
121
// Automatic cookie handling
122
await agent
123
.post('https://api.example.com/login')
124
.send({ username: 'user', password: 'pass' });
125
// Cookies from login response are automatically saved
126
127
// Cookies are automatically sent with subsequent requests
128
const data = await agent.get('https://api.example.com/protected');
129
130
// Manual cookie management (usually not needed)
131
const loginResponse = await superagent
132
.post('https://api.example.com/login')
133
.send({ username: 'user', password: 'pass' });
134
135
agent.saveCookies(loginResponse);
136
137
const request = superagent.get('https://api.example.com/protected');
138
agent.attachCookies(request);
139
const response = await request;
140
```
141
142
### Default Configuration
143
144
Set default configuration that applies to all requests made by the agent.
145
146
```javascript { .api }
147
/**
148
* Set default request configuration methods
149
* All methods from RequestBase are available as defaults
150
*/
151
Agent.prototype.use(fn): Agent;
152
Agent.prototype.on(event, listener): Agent;
153
Agent.prototype.once(event, listener): Agent;
154
Agent.prototype.set(field, value): Agent;
155
Agent.prototype.query(value): Agent;
156
Agent.prototype.type(type): Agent;
157
Agent.prototype.accept(type): Agent;
158
Agent.prototype.auth(user, password?, options?): Agent;
159
Agent.prototype.withCredentials(enabled?): Agent;
160
Agent.prototype.sortQuery(enabled?): Agent;
161
Agent.prototype.retry(count, callback?): Agent;
162
Agent.prototype.ok(fn): Agent;
163
Agent.prototype.redirects(count): Agent;
164
Agent.prototype.timeout(options): Agent;
165
Agent.prototype.buffer(enabled?): Agent;
166
Agent.prototype.serialize(fn): Agent;
167
Agent.prototype.parse(fn): Agent;
168
Agent.prototype.ca(cert): Agent;
169
Agent.prototype.key(key): Agent;
170
Agent.prototype.pfx(pfx): Agent;
171
Agent.prototype.cert(cert): Agent;
172
Agent.prototype.disableTLSCerts(): Agent;
173
```
174
175
**Usage Examples:**
176
177
```javascript
178
const agent = superagent.agent()
179
.set('User-Agent', 'MyApp/1.0')
180
.set('Authorization', 'Bearer token123')
181
.type('json')
182
.accept('json')
183
.timeout(10000)
184
.retry(2);
185
186
// All requests made by this agent will include the above defaults
187
const users = await agent.get('https://api.example.com/users');
188
const posts = await agent.get('https://api.example.com/posts');
189
190
// Override defaults for specific requests
191
const customRequest = await agent
192
.get('https://api.example.com/special')
193
.set('Accept', 'text/xml') // Overrides default json accept
194
.timeout(30000); // Overrides default timeout
195
```
196
197
### Plugin System
198
199
Use plugins with agents for shared functionality.
200
201
```javascript
202
// Custom plugin
203
function authPlugin(token) {
204
return (req) => {
205
req.set('Authorization', `Bearer ${token}`);
206
};
207
}
208
209
function retryPlugin(attempts) {
210
return (req) => {
211
req.retry(attempts);
212
};
213
}
214
215
// Apply plugins to agent
216
const agent = superagent.agent()
217
.use(authPlugin('my-token'))
218
.use(retryPlugin(3));
219
220
// All requests will have authentication and retry logic
221
const data = await agent.get('https://api.example.com/data');
222
```
223
224
## Session Management Patterns
225
226
### Authentication Session
227
228
Maintain authenticated sessions across multiple requests.
229
230
```javascript
231
class ApiClient {
232
constructor(baseUrl) {
233
this.baseUrl = baseUrl;
234
this.agent = superagent.agent()
235
.set('User-Agent', 'ApiClient/1.0')
236
.type('json')
237
.accept('json')
238
.timeout(10000);
239
}
240
241
async login(username, password) {
242
const response = await this.agent
243
.post(`${this.baseUrl}/login`)
244
.send({ username, password });
245
246
// Session cookie is automatically saved
247
return response.body;
248
}
249
250
async getProfile() {
251
// Session cookie is automatically sent
252
const response = await this.agent.get(`${this.baseUrl}/profile`);
253
return response.body;
254
}
255
256
async updateProfile(data) {
257
const response = await this.agent
258
.put(`${this.baseUrl}/profile`)
259
.send(data);
260
return response.body;
261
}
262
263
async logout() {
264
await this.agent.post(`${this.baseUrl}/logout`);
265
// Could clear cookies manually if needed
266
}
267
}
268
269
// Usage
270
const client = new ApiClient('https://api.example.com');
271
await client.login('user', 'pass');
272
const profile = await client.getProfile();
273
await client.updateProfile({ name: 'New Name' });
274
```
275
276
### Connection Pooling
277
278
Agents automatically manage connection pooling for better performance.
279
280
```javascript
281
const agent = superagent.agent()
282
.set('Connection', 'keep-alive');
283
284
// Multiple requests will reuse connections
285
const requests = Array.from({ length: 10 }, (_, i) =>
286
agent.get(`https://api.example.com/data/${i}`)
287
);
288
289
const responses = await Promise.all(requests);
290
console.log(`Made ${responses.length} requests with connection reuse`);
291
```
292
293
### Error Handling with Agents
294
295
Handle errors consistently across all agent requests.
296
297
```javascript
298
const agent = superagent.agent()
299
.ok(res => res.status < 500) // Treat 4xx as success
300
.retry(2)
301
.timeout(5000);
302
303
// Global error handling
304
agent.use((req) => {
305
req.on('error', (err) => {
306
console.error('Request error:', err.message);
307
// Custom error logging or handling
308
});
309
});
310
311
// Use agent with consistent error handling
312
try {
313
const data = await agent.get('https://api.example.com/data');
314
} catch (err) {
315
if (err.status === 401) {
316
console.log('Authentication required');
317
} else if (err.status === 404) {
318
console.log('Resource not found');
319
} else {
320
console.error('Unexpected error:', err);
321
}
322
}
323
```
324
325
### Agent Configuration Best Practices
326
327
```javascript
328
// Production agent configuration
329
const productionAgent = superagent.agent()
330
.set('User-Agent', 'MyApp/1.0.0')
331
.timeout({
332
deadline: 30000, // 30 seconds overall
333
response: 5000 // 5 seconds for first byte
334
})
335
.retry(3, (err, res) => {
336
// Custom retry logic
337
return err && (err.code === 'ECONNRESET' || err.timeout);
338
})
339
.ok(res => res.status < 400) // Only 4xx+ are errors
340
.ca(fs.readFileSync('ca-bundle.pem')) // Custom CA certificates
341
.buffer(true); // Buffer responses
342
343
// Development agent configuration
344
const devAgent = superagent.agent()
345
.set('User-Agent', 'MyApp/dev')
346
.timeout(60000) // Longer timeout for debugging
347
.disableTLSCerts() // For self-signed certificates
348
.on('request', (req) => {
349
console.log(`${req.method} ${req.url}`);
350
})
351
.on('response', (res) => {
352
console.log(`Response: ${res.status}`);
353
});
354
```