Skip to content

Instantly share code, notes, and snippets.

@ctrlaltdylan
Last active June 26, 2021 18:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrlaltdylan/4d42dc019d50528b4f789584a8a7748e to your computer and use it in GitHub Desktop.
Save ctrlaltdylan/4d42dc019d50528b4f789584a8a7748e to your computer and use it in GitHub Desktop.
Proxied Shopify GraphQL NextJS API Endpoint Example ( say that 10 times fast )
import withDb from '../../middleware/withDb'
import { get } from 'lodash'
import httpProxyMiddleware from "next-http-proxy-middleware";
import allowCors from "middleware/allowCors";
import jwt from "jsonwebtoken";
export const config = {
api: {
bodyParser: false,
},
};
var proxy = httpProxy.createProxyServer({});
const graphQlProxy = async (req, res) => {
await allowCors(req, res);
const token = get(req, "headers.authorization", "").replace(/Bearer /, "");
try {
const decoded = await jwt.verify(
token,
process.env.SHOPIFY_API_PRIVATE_KEY
);
req.sessionToken = decoded;
req.shopDomain = decoded.dest;
req.shopName = decoded.dest.replace("https://", "");
} catch (err) {
res.status(401).json({ message: err.message });
}
const shopName = req.shopName;
const shop = await req.db.collection('shops').findOne({ name: shopName });
if(!shop) {
res.status(404).json({ message: 'shop not found'});
return;
}
return httpProxyMiddleware(req, res, {
// You can use the `http-proxy` option
target: `https://${shopName}/admin/api/2019-10/graphql.json`,
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": shop.accessToken,
},
changeOrigin: true,
ws: true,
// In addition, you can use the `pathRewrite` option provided by `next-http-proxy`
pathRewrite: {
"^/api/graphql": "",
},
});
};
export default withDb(graphQlProxy)
@ctrlaltdylan
Copy link
Author

This file is located at pages/api/graphql.js which is why I had to use pathRewrite to modify the outgoing requests to match Shopify's routing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment