Skip to content
This repository has been archived by the owner on Apr 11, 2024. It is now read-only.

How to use Shopify.Utils.graphqlProxy with NextJS (API-Routes) #138

Closed
kato-takaomi-ams opened this issue Mar 16, 2021 · 2 comments
Closed

Comments

@kato-takaomi-ams
Copy link

kato-takaomi-ams commented Mar 16, 2021

I want to use Shopify.Utils.graphqlProxy with NextJS (API-Routes) without koa.

like this:
pages/api/graphql.ts

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  await Shopify.Utils.graphqlProxy(req, res);
};

But these two events do not fire.
https://github.com/Shopify/shopify-node-api/blob/bc70452e05de5f9209cdf21e0bf22edde3cce47f/src/utils/graphql_proxy.ts#L22
https://github.com/Shopify/shopify-node-api/blob/bc70452e05de5f9209cdf21e0bf22edde3cce47f/src/utils/graphql_proxy.ts#L26

I have confirmed that I can proxy with the following code.

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const session = await Shopify.Utils.loadCurrentSession(req, res);
  if (!session) {
    throw new Error("Cannot proxy query. No session found.");
  } else if (!session.accessToken) {
    throw new Error("Cannot proxy query. Session not authenticated.");
  }

  const shopName: string = session.shop;
  const token: string = session.accessToken;
  const options = {
    data: req.body,
  };
  const client = new Shopify.Clients.Graphql(shopName, token);
  const response = await client.query(options);
  res.status(200).json(response.body);
};

Could you give me some advice about this?

@paulomarg
Copy link
Contributor

That's interesting, it looks like your server is reaching the proxy after parsing the request body. The data and end events only fire once per request, so it's likely that something in your call stack is consuming those events before it reaches the proxy call.

If you're using Next.js API routes, you could maybe disable the bodyParser setting for that route, as per https://nextjs.org/docs/api-routes/api-middlewares#custom-config. That should stop the server from consuming those events before it reaches the proxy code.

Hope this helps!

@kato-takaomi-ams
Copy link
Author

@paulomarg Thank you for your advice. Rather, it was a complete answer.

It works fine with the following settings:

// With NextApiRequest, `export const config` for Shopify.Utils.graphqlProxy to trigger events.
export const config = { api: { bodyParser: false } };

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants