How to automatically get notion authentication credentials

I’m working with a React Notion integration library and need to display private pages. The setup requires authentication tokens like this:

const notionClient = new NotionService({
  userId: process.env.USER_ID,
  sessionToken: process.env.SESSION_TOKEN
})

Right now I have to manually get these values from browser cookies:

Browser Inspector > Storage > Cookies > copy session_token and user_id values

The issue is these tokens expire and change randomly. When this happens my application breaks unexpectedly and I have to manually update the environment variables and restart everything.

Is there any way to programmatically fetch these authentication tokens instead of doing it manually each time?

I need a solution that can automatically refresh or retrieve new tokens when the old ones become invalid. This would prevent the app from breaking when tokens expire.

Session tokens are unpredictable and always break at the worst times. I’ve hit this same issue on multiple projects.

Don’t bother with custom scripts or polling services. Just automate the whole token refresh cycle. Watch your API calls for auth errors and swap tokens immediately - zero downtime.

I use an automated workflow that handles browser sessions, grabs fresh tokens, and pushes them straight to your app environment. Catches failures before users see them.

Here’s how it works: monitors your Notion calls, spots stale tokens, fires up a browser to grab new credentials, updates environment variables instantly. Your React app gets the new tokens on the next call.

Latenode nails this because it combines API monitoring, browser automation, and environment management in one workflow. No custom scripts to maintain or servers to manage.

Had the exact same problem! I switched to Notion’s official API and it’s way more reliable than messing with session tokens from cookies. Those tokens aren’t meant for programmatic stuff and they’ll break on you constantly. Just create an integration in your Notion settings to get a proper API key. Use their JavaScript SDK - it handles auth cleanly and won’t randomly break when tokens expire.

just use a token watcher script. mine pings notion every 10 minutes and refreshes tokens automatically when calls start failing. skip browser automation - hit their login endpoint directly with your stored creds. script dumps fresh tokens into the .env file and your app picks them up without missing a beat.

Been there. Session tokens are a pain since Notion switches up those cookies randomly.

I built an automation that handles token refreshes automatically. It watches for failed Notion calls, grabs fresh tokens, and updates my app without me touching anything.

The key is headless browser automation - logs into Notion, pulls new cookies, feeds them to your React app. No more copying from dev tools or 2am surprises.

I use Latenode for this since it does browser automation, catches API failures, and updates environment variables in one shot. Runs on schedule too, so tokens refresh before they die.

Beats manually managing cookies or fighting Notion’s API limits on private pages.

The Problem:

You’re experiencing unexpected application breakage due to expiring and randomly changing Notion authentication tokens (session_token and user_id) fetched manually from browser cookies. This requires manual intervention to update environment variables and restart your React application, leading to significant downtime and frustration. The goal is to automate the process of retrieving and refreshing these tokens to prevent interruptions.

:thinking: Understanding the “Why” (The Root Cause):

Manually fetching and updating authentication tokens is inherently unreliable. Notion’s session tokens have a limited lifespan and are subject to unpredictable changes. Directly accessing cookies through browser inspection is fragile, prone to errors, and not suitable for production applications. This approach breaks the principle of separation of concerns and introduces significant security risks by hardcoding sensitive information. A robust solution requires programmatic token management that handles authentication failures and refreshes tokens automatically.

:gear: Step-by-Step Guide:

  1. Automate Token Retrieval with Puppeteer (or Playwright): This approach uses a headless browser to log into Notion, obtain the updated tokens, and provide them to your React application. This is the most reliable way to manage Notion’s session tokens because it avoids the limitations of hardcoded values and directly interacts with the authentication system.

    const puppeteer = require('puppeteer');
    
    async function getNotionTokens() {
        const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); //Consider adding more robust options
        const page = await browser.newPage();
        await page.goto('https://www.notion.so/login'); //Navigate to Notion login
        //Add your Notion login credentials securely (avoid hardcoding, use environment variables or a secure config mechanism)
        await page.type('#email', process.env.NOTION_EMAIL);
        await page.type('#password', process.env.NOTION_PASSWORD);
        await page.click('button[type="submit"]'); //or appropriate selector for login button
        await page.waitForNavigation(); //Wait for the page to load after login.
        const cookies = await page.cookies();
        const sessionToken = cookies.find(cookie => cookie.name === 'session_token')?.value;
        const userId = cookies.find(cookie => cookie.name === 'user_id')?.value;
        await browser.close();
        if (!sessionToken || !userId) {
            throw new Error("Failed to retrieve Notion tokens");
        }
        return { sessionToken, userId };
    }
    
    //Example usage:
    getNotionTokens()
        .then(tokens => {
            console.log('Notion Tokens:', tokens);
            //Update your environment variables or a secure storage mechanism with the retrieved tokens
        })
        .catch(error => {
            console.error('Error retrieving Notion tokens:', error);
        });
    
    
  2. Securely Store and Manage Tokens: After obtaining the tokens, store them securely. Avoid hardcoding them directly into your application code. Instead, use environment variables, a dedicated secrets management service (e.g., AWS Secrets Manager, Google Cloud Secret Manager, HashiCorp Vault), or a secure configuration store.

  3. Implement Token Refresh Logic: Integrate the getNotionTokens() function into your application’s authentication flow. You might want to add a mechanism to refresh tokens proactively (e.g., periodically check for expiration or use token expiration data from the Notion API response headers) before they become invalid, or reactively (e.g., handle 401 Unauthorized errors).

  4. Error Handling and Logging: Implement robust error handling to gracefully manage authentication failures. Log any errors that occur during token retrieval or refresh to aid in debugging.

  5. User Agent Spoofing (Consideration): Notion might have mechanisms to detect automated requests. If you encounter issues, consider adding realistic delays, user-agent spoofing, and other anti-bot countermeasures to your Puppeteer script (see Puppeteer’s documentation for details).

:mag: Common Pitfalls & What to Check Next:

  • Notion’s Rate Limits: Be mindful of Notion’s API rate limits. Excessive requests might lead to temporary account suspension. Implement appropriate rate limiting in your code.
  • Security Best Practices: Never hardcode your Notion credentials in your application. Utilize secure storage and environment variable management.
  • Puppeteer Setup: Ensure you have Puppeteer correctly installed (npm install puppeteer) and potentially handle the download of Chromium separately depending on your system.
  • Selector Updates: The CSS selectors used in the getNotionTokens function might need updates if Notion changes its website layout. Regularly check and adapt your code to maintain functionality.
  • Authentication Failures: If token retrieval fails, carefully review your Notion credentials, network connectivity, and the Puppeteer code for errors.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Set up a token rotation service that watches for auth failures in your API calls. I use middleware that catches failed requests and auto-refreshes tokens before retrying. The key is building a fallback that detects tokens about to expire from response patterns - don’t wait for complete failure. Build a simple Node service that keeps a token pool, refreshes credentials ahead of time, and serves valid tokens to your React app via local endpoint. Your app never touches expired tokens, so no sudden breakage. The service handles all the browser automation mess while your main app stays clean.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.