Search code examples
javascriptnode.jsshopifyshopify-appshopify-api-node

Building Shopify Ap with React and Node issue


i am following along with the Shopify app dev how-to provided by shopify but keep getting an error with my localhost saying - external server error, the cause in terminal says 'Context has not been properly initialized. Please call the .initialize() method to setup your app context object.' but not sure how to do this in my server.js file below;

require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');

dotenv.config();

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY } = process.env;

app.prepare().then(() => {
  const server = new Koa();
  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',
        'write_products',
        'read_script_tags',
        'write_script_tags'
      ],
      afterAuth(ctx){
        const { shop, accessToken } = ctx.session;

        ctx.redirect('/');
      },
    }),
  );

  server.use(verifyRequest());
  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}`);
  });
});

Solution

  • Some things have been updated with Shopify's app development (depending on your packages version).

    You now need to init a Shopify context.

    // ...
    
    const { default: Shopify, ApiVersion } = require('@shopify/shopify-api');
    
    // ...
    
    Shopify.Context.initialize({
      API_KEY: process.env.SHOPIFY_API_KEY,
      API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
      SCOPES: process.env.SHOPIFY_API_SCOPES.split(","),
      HOST_NAME: process.env.SHOPIFY_APP_URL.replace(/https:\/\//, ""),
      API_VERSION: ApiVersion.October20,
      IS_EMBEDDED_APP: true,
      SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
    });
    
    // ...
    

    You will of course need to apply other small updates to your server.js file.

    For more precision you can look directly into the official Shopify React/Node app dev tuto source code : https://github.com/Shopify/shopify-app-node/blob/tutorial_listen_for_store_events/server.js