simple-koa-shopify-auth
simple-koa-shopify-auth copied to clipboard
Validate the request from Frontend
In my Koajs backend, i have setup a route which is invoked from the embedded app (ex. a button click).
Koajs backend route
import Router from 'koa-router';
import { verifyRequest } from 'simple-koa-shopify-auth';
const verifyApiRequest = verifyRequest({ returnHeader: true });
const appRouter = new Router();
appRouter.get('/api/app/test', verifyApiRequest, async (ctx) => {
ctx.body = { message: 'Request recevied' };
});
export default appRouter;
And in the embedded app, I used the axios client to make the request and i have added the session token in the request header as follow.
import React from 'react';
import { Page, Layout, Card, Button } from '@shopify/polaris';
import { useAppBridge } from '@shopify/app-bridge-react';
import { getSessionToken } from '@shopify/app-bridge-utils';
import axios from 'axios';
const Home = () => {
const app = useAppBridge();
const onClick = async () => {
// Create axios instance for authenticated request
const authAxios = axios.create();
// intercept all requests on this axios instance
authAxios.interceptors.request.use((config) => {
return getSessionToken(app)
.then((token) => {
// append your request headers with an authenticated token
console.log(`token: ${ token }`);
config.headers["Authorization"] = `Bearer ${ token }`;
config.headers["Content-Type"] = `application/json`;
return config;
});
});
authAxios.get('/api/app/test')
.then(result => console.log(result))
.catch(error => console.log(error))
};
return (
<Page title="Home">
<Layout>
<Layout.AnnotatedSection
title="Home page"
description="This is the home page."
>
<Card sectioned>
<p>Home</p>
<Button onClick={ onClick }>Click me</Button>
</Card>
</Layout.AnnotatedSection>
</Layout>
</Page>
);
};
export default Home;
I still got 401 bad request when clicking the btn from the frontend. But it works if i remove the verifyApiRequest in the route. i.e.
...
appRouter.get('/api/app/test', async (ctx) => {
ctx.body = { message: 'Request recevied' };
});
...
Anything i have missed? Thanks.