question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Something people seem to trip over a bit is the fact that session, despite being a writable store, doesn’t get persisted. I wonder if we can address that:

<script>
  import { stores } from '$tbd';
  const { session } = stores();

  let name;

  async function update_username(name) {
    // optimistic — update the client-side store, then persist
    // (rolls back in case of failure)
    session.update($session => ({
      ...$session,
      user: { ...$session.user, name }
    }));

    session.persist();

    // pessimistic — wait until success before updating
    // client-side store
    session.persist($session => {
      ...$session,
      user: { ...$session.user, name }
    });
  }
</script>

<!-- pretend i did this properly, with a progressively enhanced <form> -->
<input bind:value={name}>
<button on:click={() => update_username(name)}>
  Update
</button>

This requires that the developer add some persistence logic. Perhaps in the same file where we define logic for getting a session (#9), we have a place to put logic for persistence:

// src/session/index.js
import { parse } from 'cookie';
import * as db from './db.js';

export async function get(headers) {
  const cookies = parse(headers.cookie);
  const user = await db.get(cookies.session_id);
  return { user };
}

export async function persist(headers, data) {
  const cookies = parse(headers.cookie);
  const user = await db.set(cookies.session_id, data); // validate and store
  return { user };
}

Glossing over some details but what do folks think?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:17 (17 by maintainers)

github_iconTop GitHub Comments

1reaction
Rich-Harriscommented, Oct 21, 2020

maybe there should be more specialized support for authentication/authorization instead?

Authentication definitely needs to be made as simple as possible, because at present it’s a nightmare (not just in Sapper apps, but generally). I don’t know that it can be solved at the framework level though without introducing a lot of opinions. I think the best we can do is provide a flexible enough API that it’s easy to plug in packages that deal with authentication.

What other use cases are there?

Shopping carts? I’m new to the site, browsing as a guest, I want my cart to persist even though I haven’t registered/logged in yet:

export async function get(headers) {
  const cookies = cookie.parse(headers['cookie']);

  const user = await db.get_user(cookies.session_id);
  const cart = await (user ? db.get_cart_for_user(user.id) : db.get_cart_for_guest(cookies.session_id));

  return {
    user: user && {
      // only expose public info
      name: user.name,
      email: user.email,
      avatar: user.avatar
    },
    cart
  };
}

Of course you could have a /cart.json endpoint instead, but it would be slightly more complicated as you’d need some way to represent individuals who aren’t logged in without exposing their cookies.

only keying it on a random session ID feels potentially dangerous

Can you elaborate? This is just how auth works, no?

would we need to worry about to how to clear old, expired sessions from storage?

I don’t think it need be solved at the framework level — I’m imagining that the implementation of db.get_user above (for example) would check to see if the session was expired. Periodically you’d want to purge expired sessions from the database to save space, but this can happen whenever (e.g. svelte.dev purges expired sessions whenever the server starts, i.e. whenever we deploy a new version)


This is a bit of a tangent, but: speaking of shopping carts, one of my bugbears with a lot of ecommerce sites is that I often want to look at products in multiple tabs, which means my cart usually gets out of sync between them. Is there a case where you wouldn’t want sessions to be synchronised across tabs with localStorage events? (or, going further, using similar logic to SWR?)


This is also tangential to session.persist, but a couple of things occur to me:

  • the example code thus far takes a headers argument. Should it just be a pre-parsed cookies object? You might want to use Authorization headers with endpoints, for example, but they’re not much help when browsing to a page. Feels like just passing cookies would simplify things somewhat
  • there’s currently no place to set headers['cookie'], which seems like a bit of an oversight
1reaction
ehrencronacommented, Oct 21, 2020

It would be helpful to think about this in terms of which use cases it would support. The Sapper docs and the examples above only talk about storing the current user, but if that’s the main use case maybe there should be more specialized support for authentication/authorization instead?

You could imagine using this for storing settings (e.g. dark mode) you want available on the server side, but as soon as you have authentication you’d want to store the settings with the user rather than the session.

What other use cases are there?

A couple of other aspects:

  • if we offer endpoints for storing and retrieving potentially personal data we’d need to worry about security; only keying it on a random session ID feels potentially dangerous
  • would we need to worry about to how to clear old, expired sessions from storage?
Read more comments on GitHub >

github_iconTop Results From Across the Web

Sessions
Sessions is the platform for hosting stand-out meetings and webinars. ... Sessions provides everything you need to conduct effective meetings,
Read more >
Sessions at the Presidio – TO GO MENU – COCKTAILS ...
We will be closed for the holiday on December 25th & 26th reopening on December 27th at 11:30am. For reservations, please visit OpenTable....
Read more >
Sessions MFG
Sessions MFG is a snowboard outerwear manufacturer of premium jackets, pants, and lifestyle apparel - Always Have Always Will.
Read more >
Sessions West Coast Deli
CHRISTMAS ZEPHYR ; Newport Beach. ADDRESS: 2823 Newport Blvd. Newport Beach, CA 92663. PHONE: 949-220-9001. HOURS: 8am-6pm Daily ; Huntington Beach. Address: 414 ......
Read more >
Sessions College
Sessions College is an accredited fully online college offering degree and certificate programs in art, design and photography.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found