Skip to content

Commit 420013d

Browse files
authored
docs: add section about session refresh (#16)
1 parent d5b94f9 commit 420013d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/partials/document/connection.html.md

+43
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,49 @@ const res = await conn.oauth2.refreshToken(refreshToken)
110110
console.log(res.access_token)
111111
```
112112

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+
const jsforce = require('jsforce');
121+
122+
const conn = new jsforce.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+
await conn.login(username, password);
129+
if (!conn.accessToken) {
130+
throw new Error('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 instanceof Error) {
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.
155+
113156

114157
### Logout
115158

0 commit comments

Comments
 (0)