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

Viewed 536

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 }) => {

        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 ?

Any kinds of suggestion are highly appreciated. Thanks

0 Answers
Related