Type-safe session for all Astro SSR project

Overview

Astro Session

Why use Astro Session?

When building server application with Astro, you will often need session system to identify request coming from the same user. It's commonly used for authenticating users.

Astro Session provide a per route basis API to manage session on different provider (highly inspired by Remix).

In addition, we leverage TypeScript to provide a fully type-safe session system across your project.

Getting Started

Settings up a session storage

We recommend setting up you session storage in src/session.ts.

// src/session.ts
import { createCookieSessionStorage } from "astro-session";

// your session data type which define the shape of your session data
export type SessionData = {
  count: number;
  user: User | null;
};

export const { getSession, commitSession } =
  createCookieSessionStorage<SessionData>(
    { count: 0, user: null }, // the default value on new session created, this must match your SessionData

    {
      cookie: {
        // all of these are optional
        name: "__session-id",
        path: "/",
        secret: "not-secret", // even if optional, this is mandatory when passing your app in production
      },
    }
  );

Using the session in an astro file

The input/output to a session storage object are HTTP cookies. getSession() retrieves the current session from the incoming request's Cookie header, and commitSession()/destroySession() provide the Set-Cookie header for the outgoing response.

---
// src/pages/index.astro
import { getSession, commitSession } from "../session"

// get the session
const session = await getSession(Astro.request);

// update specific value in the session
session.set('count', session.get('count') + 1);
// or
// session.set('count', (value) => value + 1);

// get specific value in the session
const count = session.get('count');

// save the session in the cookie (mandatory to persist data from one request to another)
Astro.response.headers.set("set-cookie", await commitSession(session));
---

<p>You visited this page: {{ count }}</p>

Using session in a API endpoint

A login workflow might look like this:

// src/routes/api/login.ts
import type { APIContext } from "astro";
import { commitSession, getSession } from "../../utils/session";

export async function post({ request }: APIContext) {
  const session = await getSession(request);
  const formData = await request.formData();

  const email = formData.get("email");
  const password = formData.get("password");

  // checks for email + password combinaison
  const user = await validateCredentials(email, password);

  if (!user) {
    // if email or password incorrect, flash a message to show the user what is the error
    session.flash("error", "Invalid email/password");

    return new Response(null, {
      status: 302,
      headers: {
        location: "/login",
        // commit the session to persist it
        "set-cookie": await commitSession(session),
      },
    });
  }

  // if the credentials are valid, save the user in session
  session.set("user", user);

  // redirect to the dashboard
  return new Response(null, {
    status: 302,
    headers: {
      location: "/dashboard",
      // commit the session to persist it
      "set-cookie": await commitSession(session),
    },
  });
}

And in our page:

---
// src/routes/login.astro
import { getSession, commitSession } from "astro-session";

const session = await getSession(Astro.request);

// if the user is already authenticated, redirect to the dashboard
if (!session.get('user')) {
  return Astro.redirect('/dashboard')
}

// get the error message if there is any and delete it after accessing it
// flash data are accessible only once and get deleted after
const error = session.flash('error');

// persist the session data
Astro.response.headers.set("set-cookie", await commitSession(session));
---

<!-- display error if there is any in the session -->
{!!error && <p>{error}</p>}

<form method="post" action="/api/login">
  <input name="email" type="email" placeholder="Email" />

  <input name="password" type="password" placeholder="Password" />

  <button type="submit">Login</button>
</form>

FAQ / Gotchas

What is the difference between normal data and flash data?

Flash data are only accessible once and are deleted just after. They are used for passing down data to the next page for success / error message for example.

Your question is not listed?

We make sure to include as much information in this section as possible. If you didn't find an answer here, feel free to open an issue with your question and we will be happy to guide you out!

Credits

Astro Session took a lot of inspirations from Remix session API and Fresh Session

You might also like...

Cloudy is a set of constructs for the AWS Cloud Development Kit that aim to improve the DX by providing a faster and type-safe code environment.

cloudy-ts These packages aren't yet published on npm. This is still highly experimental. Need to figure out a few things before releasing the first ve

Nov 3, 2022

Zero runtime type-safe CSS in the same file as components

macaron comptime-css is now called macaron! macaron is a zero-runtime and type-safe CSS-in-JS library made with performance in mind Powered by vanilla

Jan 4, 2023

A next-gen framework for type-safe command-line applications

Zors 🥇 Next-gen framework for building modern, type-safe command-line applications. 📦 Tiny (zero dependencies) 💡 Runtime agonistic (supports both D

Dec 1, 2022

A compiled-away, type-safe, readable RegExp alternative

🦄 magic-regexp A compiled-away, type-safe, readable RegExp alternative ✨ Changelog 📖 Documentation ▶️ Online playground Features Runtime is zero-dep

Jan 8, 2023

A script that combines a folder of SVG files into a single sprites file and generates type definitions for safe usage.

remix-sprites-example A script that combines a folder of .svg files into a single sprites.svg file and type definitions for safe usage. Technical Over

Nov 9, 2022

A functional, immutable, type safe and simple dependency injection library inspired by angular.

func-di English | 简体中文 A functional, immutable, type safe and simple dependency injection library inspired by Angular. Why func-di Installation Usage

Dec 11, 2022

👩‍🎤 Headless, type-safe, UI components for the next generation Web3.Storage APIs.

👩‍🎤 Headless, type-safe, UI components for the next generation Web3.Storage APIs.

Headless, type-safe, UI components for the next generation Web3.Storage APIs. Documentation beta.ui.web3.storage Examples React Sign up / Sign in Sing

Dec 22, 2022

Type safe library for interacting with Mindbody's Public API (v6) and Webhooks

Mindbody API Type safe library for interacting with Mindbody's Public API (v6) and Webhooks ⚠️ Read before installing This library is typed according

Dec 9, 2022

A fully type-safe and lightweight way of using exceptions instead of throwing errors

🛡️ exceptionally A fully type-safe and lightweight way of using exceptions instead of throwing errors 🦺 fully typesafe 🐤 lightweight (209 bytes) 🏃

Jan 4, 2023
Owner
Steven Yung
Freelance fullstack developer 🥞 | Serial unlaunched side-projects maker 🚀 | Bouldering fanatic 🧗
Steven Yung
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

alloc 54 Dec 29, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A fully type-safe and lightweight internationalization library for all your TypeScript and JavaScript projects.

?? typesafe-i18n A fully type-safe and lightweight internationalization library for all your TypeScript and JavaScript projects. Advantages ?? lightwe

Hofer Ivan 1.3k Jan 4, 2023
Primary repository for all information related to Fast-Floward Bootcamp session 1

⏩ Fast Floward Welcome to Fast Floward! We are excited to have you here. This repository is where you will find all content, resources, and links for

Decentology 44 Dec 23, 2022
Build type-safe web apps with PureScript.

PUX Build type-safe web applications with PureScript. Documentation | Examples | Chat Pux is a PureScript library for building web applications. Inter

Alex Mingoia 567 Jun 18, 2022
A zero-dependency, buildless, terse, and type-safe way to write HTML in JavaScript.

hdot A sensible way to write HTML in JavaScript. Type-safe. Helps you follow the HTML spec. Terse. Almost character for character with plain HTML. Bui

Will Martin 31 Oct 24, 2022
Type Safe Object Notation & Validation

tson Type Safe Object Notation & Validation ?? Work in Progress, not ready for production... Features ?? Functional ?? Immutable ✅ Well tested Why? Af

null 9 Aug 10, 2022