skip to Main Content

I am writing a simple server for a small app for Shopify. After getting the token for my app, I wanted to save it to session so I used express-session. However it didn’t work.

I tried this solution in the code below.

The guys over github also have this issue:

https://github.com/expressjs/session/issues/371

https://github.com/expressjs/session/issues/633

Here is my configuration:

app.use(session({ 
    secret: 'new app',
    resave: false,
    saveUninitialized: true,
    cookie: {maxAge: 24*60*60*1000}
}))

This is the code for getting token and save it:

request.post(accessTokenRequestUrl, { json: accessTokenPayload })
        .then((accessTokenResponse) => {
            const accessToken = accessTokenResponse.access_token;
            const shopRequestUrl = 'https://' + shop + '/admin/themes.json';
            const shopRequestHeaders = {
                'X-Shopify-Access-Token': accessToken,
            };

            request.get(shopRequestUrl, {headers: shopRequestHeaders})
            .then((shopRes) => {
                let shopObj = JSON.parse(shopRes)
                let themeId = shopObj.themes[0].id;


                req.session.token = accessToken;
                req.session.save();
                console.log(req.session);

                res.json({
                    themeId: themeId,
                    token: accessToken
                })
            })

        })

My console.log after this. I says that I have the token in session object:

Session {
  cookie:
   { path: '/',
     _expires: 2019-02-27T09:01:18.638Z,
     originalMaxAge: 86400000,
     httpOnly: true },
  token: '1354658af88b9417d3c268dd3c22eae4' }

However in another route:

app.get('/shopify/callback/images', (req, res) => {
    console.log(req.session);
    res.send(req.session.token);
})

I got this

Session {
  cookie:
   { path: '/',
     _expires: 2019-02-27T09:03:56.280Z,
     originalMaxAge: 86400000,
     httpOnly: true } }

Thank you so much!

2

Answers


  1. First, a Promise should always return a Promise if there is any async job in it.

    return request.get(shopRequestUrl, {headers: shopRequestHeaders})
    

    Plus, it’s a best practice to always add a .catch() in a Promises chain.

    But the real issue here is that req.session.save() is asynchronous and takes a callback function.

    req.session.token = accessToken;
    req.session.save(() => {
      console.log(req.session);
    
      return res.json({
        themeId : themeId,
        token   : accessToken,
      });
    });
    
    Login or Signup to reply.
  2. In my case, it’s because the cookies were not sent in the first place.

    I was using axios and I had to set the option { withCredentials: true } when making requests.

    I hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search