Write on session with Sapper and Svelte
Asked Answered
T

1

6

I wrote a Sapper app with session management following the RealWorld example:

polka()
  .use(bodyParser.json())
  .use(session({
    name: 'kidways-app',
    secret: 'conduit',
    resave: false,
    saveUninitialized: true,
    cookie: {
      maxAge: 31536000
    },
    store: new FileStore({
      path: 'data/sessions',
    })
  }))
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    pdfMiddleware,
    sapper.middleware({
      session: req => ({
        token: req.session && req.session.token
      })
    })
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });

Then on my _layout.sevlte:

<script context="module">
  export async function preload({ query }, session) {
    console.log('preload', session)
    return {
      // ...
    };
  }
</script>

<script>
  import { onMount, createEventDispatcher } from 'svelte';
  import { Splash } from 'project-components';
  import * as sapper from '@sapper/app';
  import { user } from '../stores';
  import client from '../feathers';

  const { session } = sapper.stores();

  onMount(async () => {
    try {
      await client.reAuthenticate();
      const auth = await client.get('authentication');
      user.set(auth.user);
      $session.token = 'test';
    } catch (e) {
    } finally {
      loaded = true;
    }
  });

  console.log($session)
</script>

<h1>{$session.token}</h1>

This work on client side rendering, but the token is still undefined on preload, making my SSR template rendering broken.

What did I missed?

Tanaka answered 22/2, 2020 at 19:18 Comment(0)
L
12

When a page renders, session is populated according to the return value of the function you specified here:

sapper.middleware({
  session: req => ({
    token: req.session && req.session.token
  })
})

So while the client may have an up-to-date token, it won't take effect on page reload unless you somehow persist the token to the server in such a way that the session middleware knows about it.

Typically you'd achieve this by having a server route, like routes/auth/token.js or something...

export function post(req, res) {
  req.session.token = req.body.token;

  res.writeHead(200, {
    'Content-Type': 'application/json'
  });

  res.end();
}

...and posting the token from the client:

onMount(async () => {
  try {
    await client.reAuthenticate();
    const auth = await client.get('authentication');
    user.set(auth.user);

    await fetch(`auth/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ token })
    });

    // writing to the session store on the client means
    // it's immediately available to the rest of the app,
    // without needing to reload the page
    $session.token = 'test';
  } catch (e) {
  } finally {
    loaded = true;
  }
});
Leveller answered 23/2, 2020 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.