Sending Requests with Fetch
#
Enable Fetch InterceptorsThe init
function call automatically adds interceptors to fetch
. So there is nothing else that needs to be done.
- Via NPM
- Via Script Tag
import SuperTokens from 'supertokens-website';
// call this when your app starts
SuperTokens.init({
apiDomain: "https://api.example.com"
});
async function doAPICalls() {
try {
// make API call as usual
let fetchConfig = { /* ... */ };
let response = await fetch("/someAPI", fetchConfig);
// handle response
if (response.status !== 200) {
throw response;
}
let data = await response.json();
let someField = data.someField;
// ...
} catch (err) {
if (err.status === 401) {
// redirect user to login
} else {
// handle error
}
}
}
supertokens.init({
apiDomain: "https://api.example.com"
});
async function doAPICalls() {
try {
// make API call as usual
let fetchConfig = { /* ... */ };
let response = await fetch("/someAPI", fetchConfig);
// handle response
if (response.status !== 200) {
throw response;
}
let data = await response.json();
let someField = data.someField;
// ...
} catch (err) {
if (err.status === 401) {
// redirect user to login
} else {
// handle error
}
}
}