# Session/Login Extractor (`pragmaticcoders/session-login-extractor`) Actor

Automates login flows and extracts session data.
Supports MFA with TOTP code.
You can use this actor if you need to access website with authentication.

- **URL**: https://apify.com/pragmaticcoders/session-login-extractor.md
- **Developed by:** [pragmaticcoders](https://apify.com/pragmaticcoders) (community)
- **Categories:** Automation, Developer tools
- **Stats:** 132 total users, 2 monthly users, 100.0% runs succeeded, 3 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## **Session Extractor**

🚀 **Automates login flows and extracts session data**

- cookies (including httpOnly)
- localStorage
- sessionStorage

### **🔹 Features**

- **Automates user actions** (click, type, sleep, TOTP)
- **Extracts session data**
- 😍 **Saves screenshots before interactions** - makes debugging easier
- **Supports custom User-Agent & Apify Proxy**
- **Smart element selection** - handles multiple elements with index or position
- **Two-Factor Authentication** - supports TOTP code generation

### **📥 Input Example**

```json
{
  "signInPageURL": "https://example.com/login",
  "steps": [
    { "action": "type", "selector": "#username", "value": "myUsername" },
    { "action": "type", "selector": "#password", "value": "mySecurePassword" },
    { "action": "click", "selector": "#login-button" },
    { "action": "sleep", "value": 2000 },
    { "action": "totp", "selector": "#totp-input", "pressEnter": true }
  ],
  "cookieDomains": ["example.com"],
  "userAgent": "Mozilla/5.0 ...",
  "totpSecret": "YOUR_TOTP_SECRET"
}
```

Session data will be stored in the default key-value store under the name `SESSION_DATA`.\
(storage name can be customized)

#### Input options:

```typescript
export interface InputSchema {
  // URL of the sign-in page
  signInPageURL: string;

  // List of user actions to perform
  steps: Step[];

  // List of domains to extract cookies from
  cookieDomains: string[];

  // Timeout for each page navigation (default: 30)
  gotoTimeout?: number;

  // Custom proxy configuration
  proxyConfiguration?: ProxyConfig;

  // Whether to use Apify Proxy
  forceCloud?: boolean;

  // Custom User-Agent
  userAgent?: string;

  // Whether to run in headless mode (default: false)
  headless?: boolean;
  
  // Custom storage name (default: 'SESSION_DATA')
  storageName?: string;

  // Secret key for TOTP code generation
  totpSecret?: string;
}
```

```typescript
export interface Step {
  // Action to perform: 'click', 'type', 'sleep', or 'totp'
  action: 'click' | 'type' | 'sleep' | 'totp';

  // CSS selector for the element
  selector?: string;

  // Value to type or sleep duration in milliseconds
  value?: string | number;
  
  // Element index if multiple elements are found
  // Can be a number, 'first', or 'last'
  eq?: 'first' | 'last' | number;
  
  // Whether element should be visible (default: true)
  visible?: boolean;
  
  // Press enter after typing value (default: false)
  pressEnter?: boolean;
  
  // Wait for navigation after step (default: false)
  waitForNavigation?: boolean;

  // Whether the step is optional (won't fail if element not found)
  optional?: boolean;
}
```

```typescript
export interface ProxyConfig {
  useApifyProxy?: boolean;
  apifyProxyGroups?: string[];
}
```

### **🔍 Action Examples**

#### Click Action

```json
// Simple click
{ "action": "click", "selector": "#submit-button" }

// Click second element when multiple matches exist
{ "action": "click", "selector": ".login-button", "eq": 1 }

// Click last element in a list
{ "action": "click", "selector": ".pagination-item", "eq": "last" }

// Click and wait for navigation
{ "action": "click", "selector": "#submit", "waitForNavigation": true }

// Optional click (won't fail if element not found)
{ "action": "click", "selector": "#cookie-banner", "optional": true }
```

#### Type Action

```json
// Simple typing
{ "action": "type", "selector": "#username", "value": "user@example.com" }

// Type and press Enter
{ "action": "type", "selector": "#password", "value": "password123", "pressEnter": true }

// Type into a specific input when multiple exist
{ "action": "type", "selector": ".input-field", "eq": "first", "value": "test" }

// Optional type (won't fail if element not found)
{ "action": "type", "selector": "#optional-field", "value": "test", "optional": true }

// Type and wait for navigation (useful for forms)
{ "action": "type", "selector": "#search", "value": "query", "pressEnter": true, "waitForNavigation": true }
```

#### Sleep Action

```json
// Wait for 2 seconds
{ "action": "sleep", "value": 2000 }

// Wait for 5 seconds (e.g., for animations or loading)
{ "action": "sleep", "value": 5000 }
```

#### TOTP Action

```json
// Generate and enter TOTP code
{ "action": "totp", "selector": "#totp-input" }

// Generate TOTP code, enter it, and press Enter
{ "action": "totp", "selector": "#totp-input", "pressEnter": true }

// Generate TOTP code and wait for navigation after submission
{ "action": "totp", "selector": "#totp-input", "pressEnter": true, "waitForNavigation": true }
```

### **📸 Screenshots**

The actor automatically takes screenshots before each interaction, making it easier to debug issues. Screenshots are saved with timestamps in the key-value store:

```
screenshot_1234567890.png
```

### **🔐 Session Data Example**

The extracted session data will look like this:

```json
{
  "cookies": {
    "example.com": [
      {
        "name": "sessionId",
        "value": "abc123",
        "domain": "example.com",
        "path": "/",
        "expires": 1234567890,
        "httpOnly": true,
        "secure": true
      }
    ]
  },
  "localStorage": {
    "theme": "dark",
    "user": "{\"id\":123,\"name\":\"John\"}"
  },
  "sessionStorage": {
    "lastPage": "/dashboard"
  }
}
```

### **🚀 Advanced Usage**

#### Multi-Step Authentication

```json
{
  "signInPageURL": "https://example.com/login",
  "steps": [
    { "action": "type", "selector": "#username", "value": "user@example.com" },
    { "action": "type", "selector": "#password", "value": "password123", "pressEnter": true },
    { "action": "sleep", "value": 2000 },
    { "action": "totp", "selector": "#totp-input", "pressEnter": true, "waitForNavigation": true }
  ],
  "cookieDomains": ["example.com"],
  "totpSecret": "YOUR_TOTP_SECRET"
}
```

#### Multiple Domain Session Extraction

```json
{
  "signInPageURL": "https://app.example.com/login",
  "steps": [
    { "action": "type", "selector": "#email", "value": "user@example.com" },
    { "action": "type", "selector": "#password", "value": "password123" },
    { "action": "click", "selector": "#submit" }
  ],
  "cookieDomains": [
    "app.example.com",
    "api.example.com",
    "auth.example.com"
  ]
}
```

#### Custom Element Selection

```json
{
  "steps": [
    // Select first matching element
    { "action": "click", "selector": ".login-option", "eq": "first" },
    
    // Select last matching element
    { "action": "click", "selector": ".consent-button", "eq": "last" },
    
    // Select element by index (0-based)
    { "action": "type", "selector": ".input-field", "eq": 2, "value": "test" }
  ]
}
```

#### Optional Steps Example

```json
{
  "signInPageURL": "https://example.com/login",
  "steps": [
    // Handle cookie consent popup if present
    { "action": "click", "selector": "#accept-cookies", "optional": true },
    
    // Close promotional overlay if it appears
    { "action": "click", "selector": ".promo-close-button", "optional": true },
    
    // Proceed with normal login flow
    { "action": "type", "selector": "#email", "value": "user@example.com" },
    { "action": "type", "selector": "#password", "value": "password123" },
    
    // Some sites have an optional 2FA reminder skip button
    { "action": "click", "selector": "#skip-2fa-setup", "optional": true },
    
    { "action": "click", "selector": "#login-button", "waitForNavigation": true }
  ],
  "cookieDomains": ["example.com"]
}
```

# Actor input Schema

## `signInPageURL` (type: `string`):

The website to get the session from. The login form should be available on the provided URL.

## `steps` (type: `array`):

The sequential steps to perform to get the session.

## `cookieDomains` (type: `array`):

Specify the domains that should get cookies from

## `gotoTimeout` (type: `integer`):

How many seconds until page.goto should wait

## `proxyConfiguration` (type: `object`):

Select proxies to be used by your actor.

## `forceCloud` (type: `boolean`):

Use this when you execute the actor locally in your machine, but fills the session storage on the Apify platform

## `userAgent` (type: `string`):

Custom User-Agent string for browser emulation

## `headless` (type: `boolean`):

Run browser in headless mode

## `storageName` (type: `string`):

Apify storage name for the session data

## `totpSecret` (type: `string`):

Secret key for generating TOTP codes (required for TOTP action)

## Actor input object example

```json
{
  "steps": [
    {
      "action": "type",
      "selector": "#email",
      "value": "..."
    },
    {
      "action": "type",
      "selector": "#password",
      "value": "..."
    },
    {
      "action": "click",
      "selector": "#submit"
    }
  ],
  "cookieDomains": [
    "domain.com",
    "subdomain.domain.com"
  ],
  "gotoTimeout": 30,
  "proxyConfiguration": {
    "useApifyProxy": true
  },
  "forceCloud": true,
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
  "headless": false,
  "storageName": "SESSION_DATA"
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "steps": [
        {
            "action": "type",
            "selector": "#email",
            "value": "..."
        },
        {
            "action": "type",
            "selector": "#password",
            "value": "..."
        },
        {
            "action": "click",
            "selector": "#submit"
        }
    ],
    "cookieDomains": [],
    "gotoTimeout": 30,
    "proxyConfiguration": {
        "useApifyProxy": true
    },
    "storageName": "SESSION_DATA"
};

// Run the Actor and wait for it to finish
const run = await client.actor("pragmaticcoders/session-login-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "steps": [
        {
            "action": "type",
            "selector": "#email",
            "value": "...",
        },
        {
            "action": "type",
            "selector": "#password",
            "value": "...",
        },
        {
            "action": "click",
            "selector": "#submit",
        },
    ],
    "cookieDomains": [],
    "gotoTimeout": 30,
    "proxyConfiguration": { "useApifyProxy": True },
    "storageName": "SESSION_DATA",
}

# Run the Actor and wait for it to finish
run = client.actor("pragmaticcoders/session-login-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "steps": [
    {
      "action": "type",
      "selector": "#email",
      "value": "..."
    },
    {
      "action": "type",
      "selector": "#password",
      "value": "..."
    },
    {
      "action": "click",
      "selector": "#submit"
    }
  ],
  "cookieDomains": [],
  "gotoTimeout": 30,
  "proxyConfiguration": {
    "useApifyProxy": true
  },
  "storageName": "SESSION_DATA"
}' |
apify call pragmaticcoders/session-login-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=pragmaticcoders/session-login-extractor",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ikIQpbceaCSz3vEYX/builds/UycYOl5LKN4ACSkwf/openapi.json
