I am making a shopify embedded app with @shopify/koa-shopify-auth I have performed as described in shopify documentation
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