FROM CACHE - en_header

Server Errors with OAuth and index routing

Solved
tfchb
Tourist
8 1 1

Hi Everyone, 

I am new to this world of developing apps, and I am facing a weird issue that I have no idea how to fix it. I have been trying different things but no luck so far. I really appreciate any insight that can help me to find the root cause. 

I am using this Tutorial as a reference. 
https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify

Context: I am building an App that has 3 pages (index, Dashboard and Settings). 
Behaviour: When I first install the App, everything works fine, It opens the Index page, I can go to the other 2 pages and no issues up to this point. 
But, when I try to go back to the index page, the App gets stuck (no errors), if I force a refresh in the browser it gives me an Internal Server Errors message, and then when I force a refresh again in the browser it works again. The behaviour is always the same. Below I am adding additional logs and code for your reference. 

I have no idea how to narrow down this issue. 
One thing I notice was the route back to the index is incorrect, as you can see in the ngrok log. It's trying "/pages/index/index.js" 

ngrok logs
tfchb_1-1616597947110.png

When forcing the first refresh in the browser, it gives me an Internal Server Error with the message below Cannot complete the OAuth process. 

 

event - build page: /dashboard
wait  - compiling...
event - compiled successfully
DEBUG: GET /_next/static/webpack/6837bcfad4df681b6062.hot-update.json
DEBUG: GET /_next/static/chunks/pages/dashboard.js              // ==> It opens the Dashboard page, no issues
DEBUG: GET /_next/static/css/styles.chunk.css?ts=1616597686254
event - build page: /settings
wait  - compiling...
event - compiled successfully
DEBUG: GET /_next/static/webpack/c11d5c83baa0d06feec7.hot-update.json
DEBUG: GET /_next/static/chunks/pages/settings.js.              // ==> It opens the Settings page, no issues
DEBUG: GET /_next/static/chunks/pages/index/index.js
DEBUG: GET /index
DEBUG: GET /auth
// ##### stop here when get stucked ###

// #### When I force the first Refresh, gives me Internal Server Error ####
DEBUG: GET /index?hmac=fc9d2a4655de5e989cc7eab23481ffae8395b51812ec437da71099408bf66cad&locale=en&new_design_language=true&session=441654fadb6ae2886e7f9aa9eabf5445f6337f98b2a92d5b37e0524227e7c3bd&shop=txxxxxxxxx.myshopify.com&timestamp=1616597792
DEBUG: GET /auth?shop=xxxxxxx.myshopify.com

  InternalServerError: Cannot complete OAuth process. Could not find an OAuth cookie for shop url: xxxxxxxx.myshopify.com
// #####

// #### After forcing another Refresh in the page, it works as expected ###
DEBUG: GET /index?hmac=87847a75433debc4595b455b8c165c9afdea5584cfc937ec4c6577076931f39b&locale=en&new_design_language=true&session=441654fadb6ae2886e7f9aa9eabf5445f6337f98b2a92d5b37e0524227e7c3bd&shop=xxxxxxxxx.myshopify.com&timestamp=1616598678
DEBUG: GET /auth?shop=xxxxxxx.myshopify.com
DEBUG: GET /auth/inline?shop=xxxxxxx.myshopify.com
DEBUG:xxxxxxxx.myshopify.com
DEBUG: read_products
DEBUG: GET /auth/callback?code=f808ea025fcaa11e3a5007d0cb42bf6f&hmac=71a069b10b927edfca487f3aedc694e83d20eeb25f6e923089e176b12ac76cea&shop=xxxxxxx.myshopify.com&state=513143702616981&timestamp=1616598685
event - build page: /
wait  - compiling...
event - compiled successfully


​

 


And then, after another page refresh, it works fine again. 

Server.js

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 { default: Shopify, ApiVersion } = require('@shopify/shopify-api');
const Router = require('koa-router');

dotenv.config();

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.January21,
    IS_EMBEDDED_APP: true,
    SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
  });

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

const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(() => {
    const server = new Koa();
    const router = new Router();
    server.keys = [Shopify.Context.API_SECRET_KEY];

    // Just for DEBUG:
    server.use(async (ctx, next) => {
      await next();
      console.log(`DEBUG: ${ctx.method} ${ctx.url}`);
    });

    server.use(
        createShopifyAuth({
          async afterAuth(ctx) {
            // Access token and shop available in ctx.state.shopify
            const { shop, accessToken, scope } = ctx.state.shopify;

            ACTIVE_SHOPIFY_SHOPS[shop] = scope;
            console.log(`DEBUG: ${shop}`)
            console.log(`DEBUG: ${ACTIVE_SHOPIFY_SHOPS[shop]}`);
            
            ctx.redirect(`/?shop=${shop}`);
          },
        }),
    );
      
    const handleRequest = async (ctx) => {
      await handle(ctx.req, ctx.res);
      ctx.respond = false;
      ctx.res.statusCode = 200;
    };

    router.get("/", async (ctx) => {
        const shop = ctx.query.shop;

        if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
          ctx.redirect(`/auth?shop=${shop}`);
        } else {
          await handleRequest(ctx);
        }

    });
  
    router.get("(/_next/static/.*)", handleRequest);
    router.get("/_next/webpack-hmr", handleRequest);
    router.get("(.*)", verifyRequest(), handleRequest);
  
    server.use(router.allowedMethods());
    server.use(router.routes());

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


Any insights or thoughts will be very helpful.  

Thanks, 

 

 

 

 

Accepted Solution (1)

Accepted Solutions
tfchb
Tourist
8 1 1

This is an accepted solution.

I found the issue. After spending a lot of time debugging the code trying to find the problem, the issue actually was in the Navigation config in the Partner portal. 

I was following this guide https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/build-your-user-interface-with....
based on this, we should have "/index" in the Nav config, but my App was routing to "index/index.js" which was breaking the App. 

After removing the "/index" from the Nav config, everything starts working as expected. 

View solution in original post

Replies 2 (2)
tfchb
Tourist
8 1 1

This is an accepted solution.

I found the issue. After spending a lot of time debugging the code trying to find the problem, the issue actually was in the Navigation config in the Partner portal. 

I was following this guide https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/build-your-user-interface-with....
based on this, we should have "/index" in the Nav config, but my App was routing to "index/index.js" which was breaking the App. 

After removing the "/index" from the Nav config, everything starts working as expected. 

dgtlmonk
Shopify Partner
18 1 4

What Nav config?