How to add middleware to shopify app routes?

Highlighted
Shopify Partner
1 0 0

Creating a shopify app with express and mongoose. The shop's domain and access tokens are saved to the database on the callback route of the install process. The index of the app is verified with the following function:

 

const verifyOAuth = query => {
    if (!query.hmac) {
        return false;
    }

    const hmac = query.hmac; 
    delete query.hmac;
    const sortedQuery = Object.keys(query).map(key => `${key}=${Array(query[key]).join(',')}`).sort().join('&');
    const calculatedSignature = crypto.createHmac('sha256', config.SHOPIFY_SHARED_SECRET).update(sortedQuery).digest('hex');
    if (calculatedSignature === hmac) {
      return true;
    }

  return false;
}

 

How can I create a middleware function for a request to access a shop's data from the mongo database. EX:

 

router.get('/content', auth, (req, res) => {
  const content = Content.findOne({shopifyDomain: 'shopify-domain-here'})
  res.send(content);
});

var auth = (req, res, next) => {
    // Get shop domain from authentication
    next();
};

Would I have to add the shop domain and hmac as a query for every get request to '/content', or should I use res.setHeader to set them as headers when the index of the app is loaded, or is there a better solution?

0 Likes