shopify invalid session token
Invalid session token - solve the annoying shopify error
If you have been working with shopify apps then you might have come across an error that says that you have an invalid session token. The reason behind this error might come from a race condition. The client tries to get some information from the server before it received a valid session token. Usually the client should have a session token, when making requests but you cannot be a 100% sure all of the time, thus the error is presented.
If you are making requests with axios then your request might look something like this:
// WRONG AND WIll LEAD TO ERROR DUE TO RACE CONDITIONS!!
axios
.get("https://test-application.test/api/endpoint")
.then(
(response: {
data: {
content: string;
};
}) => {
console.log("data:", data);
);
}
)
.catch((error) => {
console.log("ERROR:", error);
});
In order to make sure that there won't be a race condition you can intercept your client's call and add some properties to the headers. All of this can be done very easily with axios. We want to make sure that the session token is always sent to the server, and in order to create a session token you will have to install an npm package from shopify.
You will need some methods from the shopify app-bridge-utils so make sure to install the npm package @shopify/app-bridge-utils:
npm i @shopify/app-bridge-utils
const instance = axios.create();
// Intercept all requests on this axios instance
instance.interceptors.request.use(function (config) {
return getSessionToken(app).then((token) => {
config.headers["Authorization"] = `Bearer ${token}`;
return config;
});
});
instance
.get('https://test-application.test/api/endpoint')
.then(
(response: {
data: {
themeName: string;
appBlocksEnabled: string;
};
}) => {
console.log("data:", data);
setThemeName({ name: response.data.themeName });
setContentLoaded(true);
setSupportsAppBlocks(
response.data.appBlocksEnabled === "partly" ||
"completely"
? true
: false
);
}
)
.catch((error) => {
console.log("ERROR:", error);
});
And now your invalid session token error shouldn't appear anymore.
You can also watch my video right here: