Sending Requests with Fetch
With Interceptors
You can use fetch
as you regularly do using this method
import SuperTokensRequest from 'supertokens-website';
// call this when your app starts
SuperTokensRequest.init({
refreshTokenUrl: "/refresh"
});
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.fetch.init({
refreshTokenUrl: "/refresh"
});
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
}
}
}
If your API domain is different than your website domain, then be sure to add
credentials: 'include'
in thefetchConfig
Without Interceptors
If the viaInterceptor
option is false
you need to replace all your fetch
calls as shown below.
API Reference
The fetch function:SuperTokensRequest.fetch("/someAPI", config);
supertokens.fetch.fetch("/someAPI", config);
- Used to send a request to your API endpoint
- Treat it like a regular
fetch
call - There are other functions to specifically call
get
,post
,delete
andput
methods. They can be seen in the API reference page.
import SuperTokensRequest from 'supertokens-website';
SuperTokensRequest.init({
refreshTokenUrl: "/refresh",
viaInterceptor: false
});
async function doAPICalls() {
try {
// make API call as usual
let fetchConfig = { ... };
let response = await SuperTokensRequest.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.fetch.init({
refreshTokenUrl: "/refresh",
viaInterceptor: false
});
async function doAPICalls() {
try {
// make API call as usual
let fetchConfig = { ... };
let response = await supertokens.fetch.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
}
}
}
If your API domain is different than your website domain, then be sure to add
credentials: 'include'
in thefetchConfig