How to perform external api request on my koa-server, which uses @shopify/koa-shopify-auth

suzan_stha
New Member
6 0 0

I am making a shopify embedded app with ***@shopify/koa-shopify-auth*** I have performed as described in shopify [documentation][1]

app.prepare().then(() => {
const server = new Koa();
const router = new Router();
let mongoDB = process.env.MONGODB_URI || 'mongodb://127.0.0.1/etsify';
mongoose.connect(mongoDB, {
useUnifiedTopology: true,
useNewUrlParser: true
}).then(() => console.log('DB Connected!'))
.catch(err => {
console.log(`DB Connection Error: ${err.message}`);
});

server.use(session({ secure: true, sameSite: 'none' }, server));
server.keys = [SHOPIFY_API_SECRET_KEY];

server.use(

createShopifyAuth({
apiKey: SHOPIFY_API_KEY,
secret: SHOPIFY_API_SECRET_KEY,
scopes: ['read_products'],
accessMode: 'offline',
async afterAuth(ctx) {
const { accessToken } = ctx.session;

let reply = await Shop.saveShopifyShop(ctx.session.shop, accessToken).then(response => {
return response;
}).catch(error => {
return error;
});


if (reply.error === false)
return ctx.redirect(`https://${ctx.session.shop}/admin/apps/${process.env.SHOPIFY_APP_ID}`);

return ctx.body = "Error";

},
})

);

server.use(router.allowedMethods());

server.use(verifyRequest());

server.use(router.routes());
router.use(require('./routers/router').routes());

server.use(async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
return
});


server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});

});

everything is good so far. But now I have to perform api request to my server from from client side. A sample code is as under

MyApp.getInitialProps = async ({ ctx }) => {

/* this is just a sample endpoint to test *?
console.log(`${APP_URL}/connection/data`);
let data = await fetch(`${APP_URL}/etsy/connection/data${ctx.asPath}`).then(response => response.json()).then(body => {
return body;
});
}

This is the request performed from the next.js client. I am not getting the idea to pass the middleware. What header should I send to validate my request against koa-auth middleware. Or should i simply make my own middleware to perform api requests ?

I can make it work if I put th routes above shopify koa-auth middleware like this

....
/* routes position changed , now my api call is responded with data*/
router.use(require('./routers/router').routes());

server.use(

                createShopifyAuth({
                    apiKey: SHOPIFY_API_KEY,
                    secret: SHOPIFY_API_SECRET_KEY,
                    scopes: ['read_products'],
                    accessMode: 'offline',
                    async afterAuth(ctx) {
                        const { accessToken } = ctx.session;

                        let reply = await Shop.saveShopifyShop(ctx.session.shop, accessToken).then(response => {
                            return response;
                        }).catch(error => {
                            return error;
                        });


                        if (reply.error === false)
                            return ctx.redirect(`https://${ctx.session.shop}/admin/apps/${process.env.SHOPIFY_APP_ID}`);

                        return ctx.body = "Error";

                    },
                })

            );
            server.use(router.allowedMethods());
            server.use(router.routes());

Any kinds of suggestion are highly appreciated. Thanks

[1]: https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify

Reply 1 (1)

TheCodePixi
Shopify Staff (Retired)
5 3 4

Hi! Is the issue that you are not able to make any requests to the Shopify API or that you are not able to make requests to your own API/server? The middleware is already applied on the backend in `server.use( createShopifyAuth({}) )` so you should be fine there. Also, for the front end of your app, are you following the rest of the tutorial and using AppBridge on the front-end (which you will need to have the JWT access token)? 

To learn more visit the Shopify Help Center or the Community Blog.