I keep getting this error when I try to execute the following code. Basically it takes in the given refresh token and send a POST request with the URLSearchParams to the URL. But for some reason URLSearch params keeps on throwing an error.
const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token,
}),
})
return response.json()
}
where refresh_token
is a constant defined by an enviornment variable.
Argument of type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to parameter of type 'string | string[][] | Record<string, string> | URLSearchParams | undefined'.
Type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to type 'undefined'.ts(2345)
The problem is that refresh_token
is potentially undefined
and URLSearchParams
only supports fields with string values.
There are several options here...
Provide a fallback string value
new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refresh_token ?? ""
})
Add parameters optionally
const body = new URLSearchParams({ grant_type: "refresh_token" });
if (refresh_token) {
body.append("refresh_token", refresh_token);
}
If you're sure that refresh_token
is not undefined
, assert it as so
new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refresh_token!
})