1
votes

I'm working on a project using Sapper, and been struggling with something for a bit now – can't quite figure it out. I'm using Polka for my server (it was included with the sveltejs/sapper-template#rollup template so I went with it), and cookie-session for my session middleware.

Here is my Polka configuration, where I seed session data also:

polka()
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    cookieSession({ 
      name: 'session', 
      keys: [
        '6e818055-d346-4fcb-bf56-4c7d54cb04ab', 
        '60f3e980-6e9c-460d-8ea7-af1fffbdb92f'
      ]
    }),
    sapper.middleware({
      session: (req, res) => ({
        user: req.session.user
      })
    })
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });

When a user logs in, it's handled in routes/login.js essentially some profile info and tokens get set on session.user and the request is redirected back to the root path. I'm using @polka/send-type to respond. See below:

req.session.user = { 
  accessToken: access_token,
  name: first_name,
  pic: picture.data.url
};
send(res, 302, '', {
  Location: appUrl
});

There, I have a preload module for routes/index.svelte checks if session.user exists, and if so redirects to dashboard:

<script context="module">
  export async function preload(page, session) {
    const { user } = session;

    if (user) {
      return this.redirect(302, "dashboard");
    }
   }
</script>

This all works fine in dev, but when I npm run build and build for production it doesn't so well. It seems like the session.user isn't getting populated after the redirect in login.js.

The session object that I get in preload doesn't have session.user set after login, and vice versa on logout where session.user is simply set to null and the client is redirected to the root, session.user is still populated.

If I refresh the browser, session.user is in the correct state. Without a refresh – if I just logged out I can click around as if I were logged in, and if I had just logged in nothing happens as session.user is undefined.

Just not sure why it'd work on the dev build but not in production. Given that the session.user state is correct on browser refresh, I'm guessing it's not an issue with the cookie middleware configuration. Seems like I'm missing something else. Any help would be hugely appreciated!

1

1 Answers

1
votes

Sapper does indeed handle the cache headers differently for dev and production environment. That's why you are experiencing it this way.

But there is a simple solution by changing the sapper.middleware function:

    sapper.middleware({
      session: (req, res) => {
        res.setHeader('cache-control', 'no-cache, no-store')
        return { user: req.session.user }
      }
    })

This sets the cache-control as you want it.