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