🔐 Guide: Automatically Renew Your Dhan API Access Token (Google Apps Script)

Dhan’s Access Tokens are valid for 24 hours, after which they expire. To keep your scripts or trading bots running smoothly, you can automatically renew the token using the /v2/RenewToken endpoint.

This guide explains how to do it using Google Apps Script, which runs directly in the cloud—no local setup required.


:compass: Step 1: Prerequisites

You’ll need:

  1. A Dhan account (log in at web.dhan.co)
  2. Your Client ID
  3. A valid Access Token (generate from Dhan Web > Profile > Access DhanHQ APIs)

:warning: Tokens last for 24 hours. This script will help you refresh them automatically before expiry.


:puzzle_piece: Step 2: Open Google Apps Script

  1. Go to https://script.google.com
  2. Click New Project
  3. Rename it, e.g., Dhan Token Manager

:toolbox: Step 3: Add Your Credentials

At the top of your Apps Script project, click:

Extensions → Apps Script → Project Settings → Script Properties

Then add the following key-value pairs:

Property Name Value (example)
dhanClientId DHAN123456
accesstoken your 24-hour Access Token from Dhan Web

:gear: Step 4: Add the Script

Copy and paste the following code:

function renewDhanToken() {
  const scriptProperties = PropertiesService.getScriptProperties();
  const clientId = scriptProperties.getProperty('dhanClientId');
  const accessToken = scriptProperties.getProperty('accesstoken');

  const url = 'https://api.dhan.co/v2/RenewToken';
  
  const options = {
    method: 'GET', 
    headers: {
      'access-token': accessToken,
      'dhanClientId': clientId
    },
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const status = response.getResponseCode();
    const text = response.getContentText();

    Logger.log(`Status Code: ${status}`);
    Logger.log(`Response: ${text}`);

    if (status === 200) {
      const json = JSON.parse(text);
      const newToken = json.token;

      if (newToken) {
        scriptProperties.setProperty('accesstoken', newToken);
        Logger.log('✅ Dhan access token renewed and saved successfully.');
        return newToken;
      } else {
        throw new Error('No token field found in response: ' + text);
      }
    } else {
      throw new Error(`RenewToken failed: ${status} - ${text}`);
    }
  } catch (error) {
    Logger.log(`❌ Error renewing token: ${error}`);
    throw error;
  }
}

:repeat_button: Step 5: Run the Script

  1. Click the :play_button: Run button.
  2. Authorize the script the first time it runs.
  3. Open View → Logs to see the output.

If successful, you’ll see:

✅ Dhan access token renewed and saved successfully.

The new token automatically replaces the old one in your Script Properties.


:alarm_clock: Step 6: Automate Token Renewal (Optional)

To keep the token always valid, schedule this script to run daily:

  1. Go to Triggers → Add Trigger
  2. Choose renewDhanToken as the function
  3. Select “Time-driven” event
  4. Set it to run every 12 hours

Now your Dhan Access Token will renew itself automatically every day.


:receipt: Notes & Best Practices

  • Each renewal invalidates your old token immediately.
  • Only call /RenewToken when necessary (e.g., max twice a day).
  • Avoid sharing your access-token or clientId publicly.
  • Check logs regularly if using the script in production.

:brain: Example Output (from Logger)

Status Code: 200
Response: {"token":"eyJhbGciOi..."}
✅ Dhan access token renewed and saved successfully.

:magic_wand: Why Use Google Apps Script?

Because it’s free, cloud-hosted, and easy to integrate with your spreadsheets, bots, or API scripts — no servers or cron jobs needed. You can even connect it with Google Sheets to manage trading data fetched from Dhan APIs.

4 Likes

:puzzle_piece: Separate Script with Trigger Function

/**
 * Sets up a trigger to automatically renew the Dhan token every 12 hours.
 */
function setupDhanTokenTrigger() {
  // First, delete existing triggers for clean setup
  const triggers = ScriptApp.getProjectTriggers();
  for (const trigger of triggers) {
    if (trigger.getHandlerFunction() === 'renewDhanToken') {
      ScriptApp.deleteTrigger(trigger);
    }
  }

  // Create a new time-driven trigger to run every 12 hours
  ScriptApp.newTrigger('renewDhanToken')
    .timeBased()
    .everyHours(12)
    .create();

  Logger.log('🔁 Trigger created: renewDhanToken will run every 12 hours.');
}

:compass: How to Use

  1. Paste the full script into your Google Apps Script editor.
  2. Run the function setupDhanTokenTrigger() once manually.
  3. You’ll see a log entry:
🔁 Trigger created: renewDhanToken will run every 12 hours.
  1. That’s it! From now on, Google will automatically execute renewDhanToken() every 12 hours — even if you close your browser or log out.

:brain: Why This Matters

Access tokens from Dhan expire every 24 hours. Running this script every 12 hours gives you:

  • A safe margin before expiry (so your bot never breaks)
  • Fully hands-free token management
  • Automatic logging of each renewal in your Apps Script dashboard

Thanks for the code, I was able to convert into python and started a task on the server for 12 hours gap and its working. Thanks a ton.

@Sandip_Kumbhar :+1:

Please share the code here if you can so that everyone can benefit from it.

@Bishnoi Appreciate that you have taken the initiative to solve it on the user’s end. I am trying to convince Dhan to enhance the RenewToken API so that it works with an expired token. The comment can be found here. If it’s enhanced, we might not need the 12-hour cron. Everytime a call is made, if it returns an expired token then we call the RenewToken api to get the new token. The only thing that needs to be handled is that only 1 thread gets the new token.