Skip to main content
Efficiently managing cookies is essential for maintaining authenticated sessions and avoiding suspicious repeated logins. Twikit provides several methods to save, load, and manipulate cookies.

Why manage cookies?

Each time you call the login() method, Twitter monitors the authentication request. Repeated logins from the same account can trigger security alerts and potentially lead to account suspension. By saving and reusing cookies, you can:
  • Avoid repeated login requests
  • Maintain persistent sessions across application restarts
  • Reduce the risk of triggering Twitter’s anti-bot detection
  • Speed up your application startup time
Avoid calling login() repeatedly. Always save cookies after login and reuse them in subsequent sessions.
Twikit provides four methods for cookie management:

get_cookies()

Retrieve the current cookies as a dictionary:
from twikit import Client

client = Client()
await client.login(
    auth_info_1='username',
    password='password'
)

# Get cookies as a dictionary
cookies = client.get_cookies()
print(cookies)
# {'ct0': 'xxx...', 'auth_token': 'xxx...', ...}
This method returns all cookies stored in the current session. You can inspect, modify, or store them as needed.

save_cookies(path)

Save cookies to a file in JSON format:
# Login once and save cookies
await client.login(
    auth_info_1='username',
    password='password'
)

# Save to file
client.save_cookies('cookies.json')
The cookies are saved as a JSON file at the specified path:
{
  "ct0": "xxx...",
  "auth_token": "xxx...",
  "guest_id": "xxx...",
  "personalization_id": "xxx..."
}
Parameters:
  • path (str): The file path where cookies will be stored

load_cookies(path)

Load cookies from a previously saved file:
from twikit import Client

client = Client()

# Load saved cookies instead of logging in
client.load_cookies('cookies.json')

# Now you can make authenticated requests
user = await client.get_user_by_screen_name('example')
print(user.name)
This method reads the JSON file and restores the cookies to the client session. Parameters:
  • path (str): The file path where cookies are stored

set_cookies(cookies, clear_cookies=False)

Manually set cookies using a dictionary:
import json

# Load cookies from file manually
with open('cookies.json', 'r', encoding='utf-8') as f:
    cookies = json.load(f)

# Set the cookies
client.set_cookies(cookies)

# Or clear existing cookies first
client.set_cookies(cookies, clear_cookies=True)
Parameters:
  • cookies (dict): Dictionary of cookies to set
  • clear_cookies (bool): If True, clears existing cookies before setting new ones (default: False)
Follow this pattern to minimize login requests:
1

First time: Login and save

When running your application for the first time, login and save cookies:
import asyncio
from twikit import Client

async def first_time_setup():
    client = Client()
    
    # Login once
    await client.login(
        auth_info_1='username',
        auth_info_2='[email protected]',
        password='password'
    )
    
    # Save cookies for future use
    client.save_cookies('cookies.json')
    print('Cookies saved!')

asyncio.run(first_time_setup())
2

Subsequent runs: Load cookies

On subsequent runs, load the saved cookies instead of logging in:
import asyncio
from twikit import Client

async def main():
    client = Client()
    
    # Load saved cookies
    client.load_cookies('cookies.json')
    
    # Use the client with loaded session
    tweets = await client.search_tweet('python', 'Latest')
    for tweet in tweets:
        print(tweet.text)

asyncio.run(main())
3

Handle expired cookies

Implement error handling for expired cookies:
import asyncio
import os
from twikit import Client
from twikit.errors import Unauthorized

async def main():
    client = Client()
    
    # Try to load cookies if they exist
    if os.path.exists('cookies.json'):
        client.load_cookies('cookies.json')
    else:
        # First time: login and save
        await client.login(
            auth_info_1='username',
            password='password'
        )
        client.save_cookies('cookies.json')
    
    try:
        # Test if cookies are still valid
        await client.user_id()
    except Unauthorized:
        # Cookies expired, login again
        print('Cookies expired, logging in again...')
        await client.login(
            auth_info_1='username',
            password='password'
        )
        client.save_cookies('cookies.json')

asyncio.run(main())
Cookies are stored as a JSON file with key-value pairs. Important cookies include:
{
  "auth_token": "Authentication token",
  "ct0": "CSRF token",
  "guest_id": "Guest user identifier",
  "personalization_id": "Personalization identifier",
  "kdt": "Key distribution token",
  "twid": "Twitter user ID"
}
Key cookies:
  • auth_token: Main authentication token (most important)
  • ct0: CSRF token used for request validation
  • guest_id: Anonymous session identifier
  • personalization_id: User personalization data

Session persistence

Long-term storage

For production applications, consider storing cookies in a database:
import json
from twikit import Client

class CookieStore:
    def __init__(self, db_connection):
        self.db = db_connection
    
    def save_cookies(self, account_id, cookies):
        cookie_json = json.dumps(cookies)
        self.db.execute(
            'INSERT OR REPLACE INTO cookies (account_id, data) VALUES (?, ?)',
            (account_id, cookie_json)
        )
    
    def load_cookies(self, account_id):
        result = self.db.execute(
            'SELECT data FROM cookies WHERE account_id = ?',
            (account_id,)
        ).fetchone()
        return json.loads(result[0]) if result else None

async def main():
    store = CookieStore(db_connection)
    client = Client()
    
    # Load from database
    cookies = store.load_cookies('user123')
    if cookies:
        client.set_cookies(cookies)
    else:
        await client.login(...)
        store.save_cookies('user123', client.get_cookies())

Multiple accounts

Manage cookies for multiple accounts:
import asyncio
from twikit import Client

ACCOUNTS = [
    {'username': 'account1', 'password': 'pass1', 'cookies_file': 'cookies1.json'},
    {'username': 'account2', 'password': 'pass2', 'cookies_file': 'cookies2.json'},
    {'username': 'account3', 'password': 'pass3', 'cookies_file': 'cookies3.json'},
]

async def init_account(account):
    client = Client()
    
    try:
        client.load_cookies(account['cookies_file'])
        # Verify cookies work
        await client.user_id()
    except:
        # Login if cookies don't exist or are invalid
        await client.login(
            auth_info_1=account['username'],
            password=account['password']
        )
        client.save_cookies(account['cookies_file'])
    
    return client

async def main():
    # Initialize all accounts
    clients = await asyncio.gather(*[
        init_account(account) for account in ACCOUNTS
    ])
    
    # Use the clients
    for i, client in enumerate(clients):
        user = await client.user()
        print(f'Account {i + 1}: {user.screen_name}')

asyncio.run(main())

Security considerations

Cookies contain sensitive authentication data. Protect them carefully!

Best practices

  1. Never commit cookies to version control Add to .gitignore:
    cookies.json
    *.cookies
    
  2. Encrypt cookies at rest
    from cryptography.fernet import Fernet
    import json
    
    class EncryptedCookieStore:
        def __init__(self, key):
            self.cipher = Fernet(key)
        
        def save_cookies(self, path, cookies):
            data = json.dumps(cookies).encode()
            encrypted = self.cipher.encrypt(data)
            with open(path, 'wb') as f:
                f.write(encrypted)
        
        def load_cookies(self, path):
            with open(path, 'rb') as f:
                encrypted = f.read()
            data = self.cipher.decrypt(encrypted)
            return json.loads(data)
    
  3. Set appropriate file permissions
    import os
    
    client.save_cookies('cookies.json')
    # Make file readable only by owner
    os.chmod('cookies.json', 0o600)
    
  4. Use environment-specific storage
    import os
    
    env = os.getenv('ENVIRONMENT', 'development')
    cookies_path = f'cookies.{env}.json'
    client.save_cookies(cookies_path)
    
  5. Rotate cookies regularly Periodically re-login to get fresh cookies:
    import time
    import os
    
    COOKIE_MAX_AGE = 7 * 24 * 60 * 60  # 7 days
    
    cookies_file = 'cookies.json'
    
    # Check if cookies are old
    if os.path.exists(cookies_file):
        file_age = time.time() - os.path.getmtime(cookies_file)
        if file_age > COOKIE_MAX_AGE:
            print('Cookies are old, logging in again...')
            await client.login(...)
            client.save_cookies(cookies_file)
        else:
            client.load_cookies(cookies_file)
    

Troubleshooting

Cookies not working after load

If loaded cookies don’t work, they may have expired:
from twikit.errors import Unauthorized

try:
    client.load_cookies('cookies.json')
    await client.user_id()  # Test the session
except (Unauthorized, FileNotFoundError):
    print('Cookies invalid or missing, logging in...')
    await client.login(...)
    client.save_cookies('cookies.json')
Handle JSON decode errors:
import json

try:
    client.load_cookies('cookies.json')
except json.JSONDecodeError:
    print('Cookie file corrupted, logging in...')
    await client.login(...)
    client.save_cookies('cookies.json')

Cookies cleared unexpectedly

If cookies are being cleared, check for:
  • Calls to client.http.cookies.clear()
  • The clear_cookies=True parameter in set_cookies()
  • Multiple client instances overwriting the same file
When using the cookies_file parameter in login(), cookies are automatically saved and loaded:
await client.login(
    auth_info_1='username',
    password='password',
    cookies_file='cookies.json'
)
If cookies.json exists, it will be loaded instead of logging in.

Build docs developers (and LLMs) love