Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Invalid Session Token

Invalid Session Token

rac2
Shopify Partner
1 0 0

Hi,

I am currently developing a checkout ui extension. I want to make an API call to my backend. I get the sessionToken on the client side and pass it in the headers of the request. Unfortunately, it doesn't work and a 403 error returns. I see that it is printed in my server log:

[shopify-app/INFO] Running validateAuthenticatedSession
[shopify-app/INFO] Session was not valid. Redirecting to.....

 

This is the code from both the client and the server:

/* eslint-disable no-unused-vars */
/* eslint-disable react/react-in-jsx-scope */
import {
	Banner,
	Checkbox,
	Button,
	Form,
	BlockSpacer,
	useApi,
	reactExtension,
} from '@shopify/ui-extensions-react/checkout';
import { useState, useEffect } from 'react';

export default reactExtension('purchase.checkout.block.render', () => <Extension />);

function Extension() {
	const { lines, sessionToken } = useApi();
	
	const handleClick = async () => {
		const token = await sessionToken.get();
		console.log(token);
		try {
			const response = await fetch(
				'<My_Backend_Url>/api/save',
				{
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						Authorization: `Bearer ${token}`,
					},
					body: JSON.stringify({ data: 'data' }),
				}
			);

			if (response.ok) {
				const data = await response.json();
				console.log('Success!', data.message);
			} else {
				const error = await response.text();
				console.error('Error', error);
			}
		} catch (error) {
			console.error('Error making API call:', error);
		}
	};
//...
import { join } from 'path';
import { readFileSync } from 'fs';
import express from 'express';
import serveStatic from 'serve-static';

import shopify from './shopify.js';
import webhooks from './webhooks.js';

const PORT = parseInt(process.env.BACKEND_PORT || process.env.PORT, 10);

const STATIC_PATH =
	process.env.NODE_ENV === 'production'
		? `${process.cwd()}/frontend/dist`
		: `${process.cwd()}/frontend/`;

const app = express();
// Set up Shopify authentication and webhook handling
app.get(shopify.config.auth.path, shopify.auth.begin());
app.get(
	shopify.config.auth.callbackPath,
	shopify.auth.callback(),
	shopify.redirectToShopifyOrAppRoot()
);
app.post(
	shopify.config.webhooks.path,
	// @ts-ignore
	shopify.processWebhooks({ webhookHandlers: webhooks })
);

// All endpoints after this point will require an active session
app.use('/api/*', shopify.validateAuthenticatedSession());

app.use(express.json());

app.use(serveStatic(STATIC_PATH, { index: false }));

app.use('/*', shopify.ensureInstalledOnShop(), async (_req, res) => {
	return res.set('Content-Type', 'text/html').send(readFileSync(join(STATIC_PATH, 'index.html')));
});

app.post('/api/save', async (req, res) => {
	console.log(req.body);
	res.json({
		message: 'Success!',
	});
});

app.listen(PORT);

 

Does anyone know what the problem is and how to solve it?
Thank you

Replies 4 (4)

Vaibhav22
Shopify Partner
6 0 1

Hi @rac2 
Did you solve this issue. Even I am facing the same issue.

Harelk1015
Shopify Partner
47 1 6

hey i solved, wanna team up? 🙂

Vaibhav22
Shopify Partner
6 0 1

Hi @Harelk1015,

How did you fix that issue?

Myname_sunday
Visitor
1 0 0
YET:monzaa_cib