How to cache a token in a custom node

Describe the issue/error/question

How could I cache a token between 5 minutes in the n8n custom node?

Since our target service need this token when do request it, and it will expire in 5 minutes,
then we have to recreate one.

Is there any way to keep this token? and renew it at the correct time?
We implement this logic with Redis in Django cache with Python.
But I don’t know how to do it in n8n, since I’m pretty new in TypeScript.

Please share the workflow

I’m working with a custom Node that needs special auth steps:

  1. generate a token locally from a function.
  2. attach token as a parameter when making a request.

For example, you will get a token aeqwerfas234qwer by calling the generate_token function.
then you can make a request with https://my-gllue.com/rest/clients/?private_token= aeqwerfas234qwer

We can use this token within 5 minutes, then we have to renew it.

So let me know please how you will get token? If you will generate it in function node with generate_token() then simply return it to request note

See this:

@Shirobachi Thanks for your reply.

Yes, I generate token in function like:

const token = helpers.generateTokenWithAESKey(timestamp, credentials.apiUsername, credentials.apiAesKey);

and use it in the request section

export class Gllue implements INodeType {
    description: ...;
    async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		let responseData;
		const resource = this.getNodeParameter('resource', 0) as string;
		const operation = this.getNodeParameter('operation', 0) as string;
		const credentials = await this.getCredentials('gllueApi') as IDataObject;

		const timestamp = helpers.getCurrentTimeStamp();
		const token = helpers.generateTokenWithAESKey(timestamp, credentials.apiUsername, credentials.apiAesKey);

		if (resource === 'client') {
			if (operation === 'list') {
				const options: OptionsWithUri = {
					headers: {
						'Accept': 'application/json',
					},
					method: 'GET',
					uri: `${credentials.apiHost}/rest/client/simple_list_with_ids?paginate_by=25&ordering=-id&gql=&page=1&fields='id'&private_token=${token}`,
					json: true,
				};

				responseData = await this.helpers.request(options);
			}
		}
		return [this.helpers.returnJsonArray(responseData.result.client)];
	}
}

The issue I meet is, I want to save this token outside of the node,
then other nodes can share this token within 5 minutes,
in other words, we don’t need to generate the token for every request.

So I have never been done custom node, so I can be wrong, but I know that in function node you can use static data is like storage to save data between execution and/or nodes

1 Like

@Shirobachi Thanks a lot!

Your suggestion on getWorkflowStaticData is very informative.
I guess I can use it if it works inside Node as well.

2 Likes