Handling an invalid Link Token
Catch the error in the onExit callback and refetch a new link_token for the next time the user opens Link
Occasionally, the end user may invalidate the existing link_token
that was used to open Link by taking too long to go through the flow (30+ minutes), or attempting too many invalid logins. If this happens, Link will exit with an INVALID_LINK_TOKEN
error code.
To allow your user to open Link again, recognize the error in the onExit
callback, fetch a new link_token
, and use it to reinitialize Link. You can obtain a new link_token
by making another /link/token/create
request:
1// Using Express2const express = require('express');3const app = express();4app.use(express.json());56const { Configuration, PlaidApi, PlaidEnvironments } = require('plaid');78const configuration = new Configuration({9 basePath: PlaidEnvironments[process.env.PLAID_ENV],10 baseOptions: {11 headers: {12 'PLAID-CLIENT-ID': process.env.PLAID_CLIENT_ID,13 'PLAID-SECRET': process.env.PLAID_SECRET,14 },15 },16});1718const client = new PlaidApi(configuration);1920app.post('/api/create_link_token', async function (request, response) {21 // Get the client_user_id by searching for the current user22 const user = await User.find(...);23 const clientUserId = user.id;24 const request = {25 user: {26 // This should correspond to a unique id for the current user.27 client_user_id: clientUserId,28 },29 client_name: 'Plaid Test App',30 products: ['auth'],31 language: 'en',32 webhook: 'https://webhook.example.com',33 redirect_uri: 'https://domainname.com/oauth-page.html',34 country_codes: ['US'],35 };36 try {37 const createTokenResponse = await client.linkTokenCreate(request);38 response.json(createTokenResponse.data);39 } catch (error) {40 // handle error41 }42});
For the Link web integration, reinitializing Link means creating a new iframe. To avoid stacking iframes for each Link initialization, you can clean up the old iframe by calling the destroy()
method on the Plaid Link handler.
1// Initialize Link with a new link_token each time.2const configs = {3 token: (await $.post('/create_link_token')).link_token,4 onSuccess: (public_token, metadata) => {5 // Send the public_token to your app server.6 },7 onExit: (err, metadata) => {8 // The user exited the Link flow with an INVALID_LINK_TOKEN error.9 // This can happen if the token expires or the user has attempted10 // too many invalid logins.11 if (err != null && err.error_code === 'INVALID_LINK_TOKEN') {12 linkHandler.destroy();13 linkHandler = Plaid.create({14 ...configs,15 // Fetch a new link_token because the old one was invalidated.16 token: (await $.post('/create_link_token')).link_token,17 });18 }19 // metadata contains the most recent API request ID and the20 // Link session ID. Storing this information is helpful21 // for support.22 },23};2425let linkHandler = Plaid.create(configs);
When the user is ready, they will be able to reopen Link and go through the authentication process again.