koa-shopify-auth icon indicating copy to clipboard operation
koa-shopify-auth copied to clipboard

Verify request issue , Network error: Unexpected token U in JSON at position 0

Open psppro26 opened this issue 3 years ago • 7 comments

I tried to simply upgrade this https://github.com/Shopify/shopify-demo-app-node-react to use session token instead of cookies on Shopify. So i followed this guide https://github.com/Shopify/koa-shopify-auth Migrating from cookie-based authentication to session tokens

Now my app look like :

server.js router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions _app.js

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: authenticatedFetch(app),
    fetchOptions: {
      credentials: "include"
    }
  });


  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}


class MyApp extends App {

  render() {
    const { Component, pageProps, shopOrigin } = this.props;

    const config = {
      apiKey: API_KEY,
      shopOrigin: shopOrigin,
      forceRedirect: true
    };

    return (
      <React.Fragment>
        <Head>
          <title>Shopy</title>
          <meta charSet="utf-8" />
        </Head>
        <Provider config={config}>
          <ClientRouter />
          <AppProvider i18n={translations}>
            <MyProvider Component={Component}>
            </MyProvider>
          </AppProvider>
        </Provider>
      </React.Fragment>
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    shopOrigin: ctx.query.shop
  };
};

So the problem is with apollo , i got an error

Error: Network error: Unexpected token U in JSON at position 0 and in my ngrok i got GET /auth 400 Bad Request

Normally authenticatedFetch(app) should authenticate my graphql request , but its always hitting the /auth The bearer token is here on graphql request , but i got an UNAUTHORIZED If someone can help , it's drive me crazy

psppro26 avatar Mar 21 '21 12:03 psppro26

I had similar auth loop but then whitelisting NextJS static content resolved it. Once you monitor network tab, you would understand who is initiator of those /auth routes.

router.get("(/_next/static/.*)", handleRequest); // Static content is clear
router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest);

avocadoslab avatar Mar 21 '21 12:03 avocadoslab

Already here and issue still occurs :/ :


  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;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });
  router.post(
    "/graphql",
    verifyRequest({ accessMode: "offline" }),
    async (ctx, next) => {
      console.log(ctx);
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );
  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions

psppro26 avatar Mar 21 '21 12:03 psppro26

I got some news , issue is same https://community.shopify.com/c/Shopify-APIs-SDKs/Offline-Access-Token-will-cause-session-not-found/m-p/1101413/thread-id/64105

work perfectly on online mode but error Error: Cannot proxy query. No session found. on offline mode

psppro26 avatar Mar 21 '21 13:03 psppro26

@psppro26 await Shopify.Utils.graphqlProxy(ctx.req, ctx.res); works in only accessMode: "online". You can not switch it to accessMode: "offline".

cf. https://github.com/Shopify/shopify-node-api/issues/140

this is actually done by design

kato-takaomi-ams avatar Mar 22 '21 00:03 kato-takaomi-ams

I tried to simply upgrade this https://github.com/Shopify/shopify-demo-app-node-react to use session token instead of cookies on Shopify. So i followed this guide https://github.com/Shopify/koa-shopify-auth Migrating from cookie-based authentication to session tokens

Now my app look like :

server.js router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions _app.js

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: authenticatedFetch(app),
    fetchOptions: {
      credentials: "include"
    }
  });


  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}


class MyApp extends App {

  render() {
    const { Component, pageProps, shopOrigin } = this.props;

    const config = {
      apiKey: API_KEY,
      shopOrigin: shopOrigin,
      forceRedirect: true
    };

    return (
      <React.Fragment>
        <Head>
          <title>Shopy</title>
          <meta charSet="utf-8" />
        </Head>
        <Provider config={config}>
          <ClientRouter />
          <AppProvider i18n={translations}>
            <MyProvider Component={Component}>
            </MyProvider>
          </AppProvider>
        </Provider>
      </React.Fragment>
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    shopOrigin: ctx.query.shop
  };
};

So the problem is with apollo , i got an error

Error: Network error: Unexpected token U in JSON at position 0 and in my ngrok i got GET /auth 400 Bad Request

Normally authenticatedFetch(app) should authenticate my graphql request , but its always hitting the /auth The bearer token is here on graphql request , but i got an UNAUTHORIZED If someone can help , it's drive me crazy

nitesh7039 avatar Jan 04 '22 18:01 nitesh7039

Was this ever resolved? Getting the same error

suarez9093 avatar Mar 10 '22 21:03 suarez9093

Was this ever resolved? Getting the same error

Me as well getting the same error. SyntaxError: Unexpected token u in JSON at position 0

Did you find a fix?

ViktorasssIT avatar Mar 17 '22 15:03 ViktorasssIT

Note that this repo is no longer maintained and this issue will not be reviewed. Prefer the official JavaScript API library. If you still want to use Koa, see simple-koa-shopify-auth for a potential community solution.

github-actions[bot] avatar Jan 30 '23 20:01 github-actions[bot]