Last active
June 26, 2021 18:35
-
-
Save ctrlaltdylan/4d42dc019d50528b4f789584a8a7748e to your computer and use it in GitHub Desktop.
Proxied Shopify GraphQL NextJS API Endpoint Example ( say that 10 times fast )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This file is located at
pages/api/graphql.js
which is why I had to usepathRewrite
to modify the outgoing requests to match Shopify's routing.