Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/anurag-roy/kiteconnect-ts/llms.txt

Use this file to discover all available pages before exploring further.

Kite Connect uses a two-step OAuth flow to authenticate users. In the first step, you redirect the user to Zerodha’s login page. After a successful login, Zerodha redirects back to your app with a short-lived request_token. In the second step, your server exchanges that request_token — along with your api_secret — for a long-lived access_token that you use for all subsequent API calls.

The login flow

1

Generate the login URL

Call getLoginURL() to get the URL you should redirect the user to. The URL includes your api_key and the API version as query parameters.
import { KiteConnect } from 'kiteconnect-ts';

const kc = new KiteConnect({
  api_key: 'YOUR_API_KEY',
});

const loginUrl = kc.getLoginURL();
// Redirect the user to loginUrl
// e.g. https://kite.zerodha.com/connect/login?api_key=YOUR_API_KEY&v=3
2

Receive the request_token

After the user logs in, Zerodha redirects them to your registered redirect URL with a request_token in the query string:
https://your-app.com/callback?request_token=XXXXXX&action=login&status=success
Extract the request_token from the query parameters on your server before proceeding.
3

Exchange for an access_token

Call generateSession() with the request_token and your api_secret. This call computes an SHA-256 checksum of api_key + request_token + api_secret and posts it to the Kite Connect token endpoint. On success it returns a SessionData object containing the access_token and sets the token on the kc instance automatically.
import { KiteConnect, SessionData } from 'kiteconnect-ts';

const kc = new KiteConnect({
  api_key: 'YOUR_API_KEY',
});

try {
  const session: SessionData = await kc.generateSession(
    'request_token_from_callback',
    'YOUR_API_SECRET'
  );

  console.log('Access token:', session.access_token);
  console.log('User ID:', session.user_id);
  console.log('Login time:', session.login_time);
} catch (error) {
  console.error('Authentication failed:', error);
}
Access tokens expire at 6 AM on the next trading day as a regulatory requirement. You must complete the login flow again each day to obtain a fresh token.

Persisting and reusing the access token

After your first successful generateSession() call, save the access_token in a database or server-side session. On subsequent requests — after the token has been persisted — initialize KiteConnect with both the api_key and the stored access_token, or call setAccessToken() explicitly.
import { KiteConnect } from 'kiteconnect-ts';

// Option 1: pass access_token at initialization
const kc = new KiteConnect({
  api_key: 'YOUR_API_KEY',
  access_token: 'STORED_ACCESS_TOKEN',
});

// Option 2: set it after initialization
const kc2 = new KiteConnect({ api_key: 'YOUR_API_KEY' });
kc2.setAccessToken('STORED_ACCESS_TOKEN');
Store the access_token in a secure location such as a database row tied to the user’s session, an encrypted server-side cookie, or a secrets manager. Never store it in localStorage or expose it to the browser.

Handling session expiry

Rather than catching TokenException errors on every API call, register a session expiry hook once. When the Kite Connect API returns a TokenException (token expired, invalidated, or revoked), the client calls your hook automatically.
kc.setSessionExpiryHook(() => {
  // Clear the stored access token
  // Redirect the user to your login page, or initiate the OAuth flow again
  console.log('Session expired — re-authentication required');
});

Invalidating the access token (logout)

Call invalidateAccessToken() to revoke the current session. Pass an explicit token to invalidate a specific one, or call it without arguments to invalidate the token currently set on the instance.
// Invalidate the active access token
const success = await kc.invalidateAccessToken();

// Invalidate a specific token
const success2 = await kc.invalidateAccessToken('access_token_to_revoke');

Renewing the access token

If your Kite Connect app has been granted a refresh_token (available to certain approved platforms), you can obtain a new access_token without repeating the full login flow.
const session = await kc.renewAccessToken(
  'YOUR_REFRESH_TOKEN',
  'YOUR_API_SECRET'
);

// The new access_token is set on the instance automatically
console.log('New access token:', session.access_token);
To invalidate a refresh token directly:
await kc.invalidateRefreshToken('YOUR_REFRESH_TOKEN');

Validating postback webhooks

When Zerodha sends order update postbacks (webhooks) to your server, use validatePostback() to verify the checksum and confirm the payload is authentic. Pass the raw postback object and your api_secret.
app.post('/postback', (req, res) => {
  const postbackData = req.body as {
    order_id: string;
    checksum: string;
    order_timestamp: string;
  };

  const isValid = kc.validatePostback(postbackData, 'YOUR_API_SECRET');

  if (!isValid) {
    return res.status(400).json({ error: 'Invalid postback checksum' });
  }

  // Process the order update
  console.log('Valid order update for order:', postbackData.order_id);
  res.json({ status: 'ok' });
});
The checksum is computed as SHA-256(order_id + order_timestamp + api_secret). If the computed checksum does not match the one in the payload, validatePostback() returns false. If required fields are missing, it throws an error.

Build docs developers (and LLMs) love