CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-superagent

Elegant & feature rich browser / node HTTP with a fluent API

Pending
Overview
Eval results
Files

agent-sessions.mddocs/

Agent & Session Management

Agent-based session management with cookie persistence, connection pooling, and default request configuration for maintaining state across multiple requests.

Capabilities

Agent Creation

Create and configure agents for session management.

/**
 * Create a new agent with optional configuration
 * @param {object} [options] - Agent configuration options
 * @param {Buffer|string} [options.ca] - Certificate authority
 * @param {Buffer|string} [options.key] - Client key
 * @param {Buffer|string} [options.cert] - Client certificate
 * @param {Buffer|string|object} [options.pfx] - PFX certificate
 * @param {boolean} [options.rejectUnauthorized] - Whether to validate certificates
 * @returns {Agent} New agent instance
 */
function agent(options?): Agent;

/**
 * Agent constructor
 * @param {object} [options] - Agent configuration options
 */
class Agent {
  constructor(options?);
}

Usage Examples:

const superagent = require('superagent');

// Basic agent creation
const agent = superagent.agent();

// Agent with TLS configuration
const httpsAgent = superagent.agent({
  ca: fs.readFileSync('ca-cert.pem'),
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem')
});

// Agent with certificate validation disabled (not recommended for production)
const insecureAgent = superagent.agent({
  rejectUnauthorized: false
});

Agent HTTP Methods

All standard HTTP methods are available on agent instances with the same signatures as the main superagent functions.

/**
 * Agent HTTP methods - same as superagent methods but with persistent session
 */
Agent.prototype.get(url, data?, callback?): Request;
Agent.prototype.post(url, data?, callback?): Request;
Agent.prototype.put(url, data?, callback?): Request;
Agent.prototype.patch(url, data?, callback?): Request;
Agent.prototype.delete(url, data?, callback?): Request;
Agent.prototype.del(url, data?, callback?): Request;
Agent.prototype.head(url, data?, callback?): Request;
Agent.prototype.options(url, data?, callback?): Request;

Usage Examples:

const agent = superagent.agent();

// Login and get session cookie
await agent
  .post('https://api.example.com/login')
  .send({ username: 'user', password: 'pass' });

// Subsequent requests automatically include session cookies
const profile = await agent.get('https://api.example.com/profile');
const settings = await agent.get('https://api.example.com/settings');

// Update data with persistent session
await agent
  .put('https://api.example.com/profile')
  .send({ name: 'Updated Name' });

Cookie Management

Automatic cookie persistence and management across requests.

/**
 * Agent cookie jar for session persistence
 */
Agent.prototype.jar: CookieJar;

/**
 * Save cookies from response to agent's cookie jar
 * @param {Response} res - Response object containing cookies
 * @returns {Agent} Agent instance for chaining
 */
Agent.prototype.saveCookies(res): Agent;

/**
 * Attach stored cookies to request
 * @param {Request} req - Request object to attach cookies to
 * @returns {Agent} Agent instance for chaining
 */
Agent.prototype.attachCookies(req): Agent;

Usage Examples:

const agent = superagent.agent();

// Automatic cookie handling
await agent
  .post('https://api.example.com/login')
  .send({ username: 'user', password: 'pass' });
// Cookies from login response are automatically saved

// Cookies are automatically sent with subsequent requests
const data = await agent.get('https://api.example.com/protected');

// Manual cookie management (usually not needed)
const loginResponse = await superagent
  .post('https://api.example.com/login')
  .send({ username: 'user', password: 'pass' });

agent.saveCookies(loginResponse);

const request = superagent.get('https://api.example.com/protected');
agent.attachCookies(request);
const response = await request;

Default Configuration

Set default configuration that applies to all requests made by the agent.

/**
 * Set default request configuration methods
 * All methods from RequestBase are available as defaults
 */
Agent.prototype.use(fn): Agent;
Agent.prototype.on(event, listener): Agent;
Agent.prototype.once(event, listener): Agent;
Agent.prototype.set(field, value): Agent;
Agent.prototype.query(value): Agent;
Agent.prototype.type(type): Agent;
Agent.prototype.accept(type): Agent;
Agent.prototype.auth(user, password?, options?): Agent;
Agent.prototype.withCredentials(enabled?): Agent;
Agent.prototype.sortQuery(enabled?): Agent;
Agent.prototype.retry(count, callback?): Agent;
Agent.prototype.ok(fn): Agent;
Agent.prototype.redirects(count): Agent;
Agent.prototype.timeout(options): Agent;
Agent.prototype.buffer(enabled?): Agent;
Agent.prototype.serialize(fn): Agent;
Agent.prototype.parse(fn): Agent;
Agent.prototype.ca(cert): Agent;
Agent.prototype.key(key): Agent;
Agent.prototype.pfx(pfx): Agent;
Agent.prototype.cert(cert): Agent;
Agent.prototype.disableTLSCerts(): Agent;

Usage Examples:

const agent = superagent.agent()
  .set('User-Agent', 'MyApp/1.0')
  .set('Authorization', 'Bearer token123')
  .type('json')
  .accept('json')
  .timeout(10000)
  .retry(2);

// All requests made by this agent will include the above defaults
const users = await agent.get('https://api.example.com/users');
const posts = await agent.get('https://api.example.com/posts');

// Override defaults for specific requests
const customRequest = await agent
  .get('https://api.example.com/special')
  .set('Accept', 'text/xml') // Overrides default json accept
  .timeout(30000);           // Overrides default timeout

Plugin System

Use plugins with agents for shared functionality.

// Custom plugin
function authPlugin(token) {
  return (req) => {
    req.set('Authorization', `Bearer ${token}`);
  };
}

function retryPlugin(attempts) {
  return (req) => {
    req.retry(attempts);
  };
}

// Apply plugins to agent
const agent = superagent.agent()
  .use(authPlugin('my-token'))
  .use(retryPlugin(3));

// All requests will have authentication and retry logic
const data = await agent.get('https://api.example.com/data');

Session Management Patterns

Authentication Session

Maintain authenticated sessions across multiple requests.

class ApiClient {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.agent = superagent.agent()
      .set('User-Agent', 'ApiClient/1.0')
      .type('json')
      .accept('json')
      .timeout(10000);
  }

  async login(username, password) {
    const response = await this.agent
      .post(`${this.baseUrl}/login`)
      .send({ username, password });
    
    // Session cookie is automatically saved
    return response.body;
  }

  async getProfile() {
    // Session cookie is automatically sent
    const response = await this.agent.get(`${this.baseUrl}/profile`);
    return response.body;
  }

  async updateProfile(data) {
    const response = await this.agent
      .put(`${this.baseUrl}/profile`)
      .send(data);
    return response.body;
  }

  async logout() {
    await this.agent.post(`${this.baseUrl}/logout`);
    // Could clear cookies manually if needed
  }
}

// Usage
const client = new ApiClient('https://api.example.com');
await client.login('user', 'pass');
const profile = await client.getProfile();
await client.updateProfile({ name: 'New Name' });

Connection Pooling

Agents automatically manage connection pooling for better performance.

const agent = superagent.agent()
  .set('Connection', 'keep-alive');

// Multiple requests will reuse connections
const requests = Array.from({ length: 10 }, (_, i) =>
  agent.get(`https://api.example.com/data/${i}`)
);

const responses = await Promise.all(requests);
console.log(`Made ${responses.length} requests with connection reuse`);

Error Handling with Agents

Handle errors consistently across all agent requests.

const agent = superagent.agent()
  .ok(res => res.status < 500) // Treat 4xx as success
  .retry(2)
  .timeout(5000);

// Global error handling
agent.use((req) => {
  req.on('error', (err) => {
    console.error('Request error:', err.message);
    // Custom error logging or handling
  });
});

// Use agent with consistent error handling
try {
  const data = await agent.get('https://api.example.com/data');
} catch (err) {
  if (err.status === 401) {
    console.log('Authentication required');
  } else if (err.status === 404) {
    console.log('Resource not found');
  } else {
    console.error('Unexpected error:', err);
  }
}

Agent Configuration Best Practices

// Production agent configuration
const productionAgent = superagent.agent()
  .set('User-Agent', 'MyApp/1.0.0')
  .timeout({
    deadline: 30000,  // 30 seconds overall
    response: 5000    // 5 seconds for first byte
  })
  .retry(3, (err, res) => {
    // Custom retry logic
    return err && (err.code === 'ECONNRESET' || err.timeout);
  })
  .ok(res => res.status < 400) // Only 4xx+ are errors
  .ca(fs.readFileSync('ca-bundle.pem')) // Custom CA certificates
  .buffer(true); // Buffer responses

// Development agent configuration
const devAgent = superagent.agent()
  .set('User-Agent', 'MyApp/dev')
  .timeout(60000) // Longer timeout for debugging
  .disableTLSCerts() // For self-signed certificates
  .on('request', (req) => {
    console.log(`${req.method} ${req.url}`);
  })
  .on('response', (res) => {
    console.log(`Response: ${res.status}`);
  });

Install with Tessl CLI

npx tessl i tessl/npm-superagent

docs

agent-sessions.md

auth-security.md

file-uploads.md

http-methods.md

index.md

parsers-serializers.md

request-building.md

request-execution.md

response-handling.md

tile.json