Shopify / shopify-app-template-node

MIT License
883 stars 399 forks source link

Add session retrieval middleware #1172

Closed Michael-Gibbons closed 1 year ago

Michael-Gibbons commented 1 year ago

Using the following code to retrieve a session every time you need it is a bit verbose.

  const session = await Shopify.Utils.loadCurrentSession(
    req,
    res
  );

I believe it would be better to have middleware to store the session in a local like so, as well as setting the local in the verify-request middleware

import { Shopify } from "@shopify/shopify-api";

export default async function withSession(req, res, next){
  const session = await Shopify.Utils.loadCurrentSession(
    req,
    res
  );

  if(!res.locals.shopify){
    res.locals.shopify = {}
  }

  res.locals.shopify.session = session

  next()
}

usage would be like so

  app.get("/api/mySuperCoolRoute", withSession, async (req, res) => {
    const session = res.locals.shopify.session
    // do cool things with session
  });

Or if the route is using the verifyRequest middleware it would also be accessible with res.locals.shopify.session

Michael-Gibbons commented 1 year ago

PR open

Michael-Gibbons commented 1 year ago

Side note, this is a also minor optimization, currently the verify request middleware is requesting the session then that data goes into the void and we must request it again. Causing 2 requests for the same session, by storing it in a local we reduce it to 1.

cquemin commented 1 year ago

If you look over here, you'll see that we have now put all session storage implementation and the session storage interface in a different packages on the monorepo. You can either use the sa ple implementation we have there or implement your own.