You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/partials/document/connection.html.md
+43
Original file line number
Diff line number
Diff line change
@@ -110,6 +110,49 @@ const res = await conn.oauth2.refreshToken(refreshToken)
110
110
console.log(res.access_token)
111
111
```
112
112
113
+
<b>NOTE</b>: You don't need to listen to the `refresh` event and grab the new access token manually, this is done automatically (see the `Session refresh handler` section).
114
+
115
+
### Session refresh handler
116
+
117
+
You can define a function that refreshes an expired access token:
118
+
119
+
```javascript
120
+
constjsforce=require('jsforce');
121
+
122
+
constconn=newjsforce.Connection({
123
+
loginUrl :'<your Salesforce server URL (e.g. https://na1.salesforce.com) is here>',
124
+
instanceUrl :'<your Salesforce server URL (e.g. https://na1.salesforce.com) is here>',
125
+
refreshFn:async(conn, callback) => {
126
+
try {
127
+
// re-auth to get a new access token
128
+
awaitconn.login(username, password);
129
+
if (!conn.accessToken) {
130
+
thrownewError('Access token not found after login');
131
+
}
132
+
133
+
console.log("Token refreshed")
134
+
135
+
// 1st arg can be an `Error` or null if successful
136
+
// 2nd arg should be the valid access token
137
+
callback(null, conn.accessToken);
138
+
} catch (err) {
139
+
if (err instanceofError) {
140
+
callback(err);
141
+
} else {
142
+
throw err;
143
+
}
144
+
}
145
+
}
146
+
});
147
+
```
148
+
149
+
The refresh function will be executed whenever the API returns a `401`, the new access token passed in the callback will be set in the
150
+
`Connection` instance and the request will be re-issued.
151
+
152
+
`Connection.login` sets the same `refreshFn` function above in the example.
153
+
154
+
You can use this feature to handle session refresh in different OAuth methods like JWT or Client Credentials.
0 commit comments