npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

supabase-safesession

v0.1.5

Published

A secure tool designed for server-side user session management in applications using Supabase.

Downloads

139

Readme

supabase-safesession

A secure tool designed for server-side user session management in applications using Supabase.

Glossary

Background

The default Supabase auth client lacks optimal compatibility with server components, leading to potential security risks and performance issues.

Database Overload

Using Supabase's auth.getUser() method in server components triggers a unique backend request each time, potentially resulting in a large number of database queries. This can significantly slow down your system. Below is a screenshot from a Supabase dashboard showing the frequency of queries for a single user with minimal server components:

Supabase frequent queries tab

Security Concerns

The typical approach of using getUser once in middleware and then relying on getSession is problematic. The getUser method validates a JWT based solely on its format and expiry, not its authenticity, accepting any correctly formatted JWT as valid.

Alternative Approach

supabase-safesession utilizes jsonwebtoken to securely verify sessions without unnecessary database queries, focusing primarily on user ID to manage user-related data efficiently. It also handles expired tokens, leveraging Supabase to refresh tokens and update cookies accordingly.

Quick Start

Configuration

  1. Retrieve your JWT secret from the Supabase project settings (API tab) and add it to your .env file.

Setup

  1. Install the package:
npm i supabase-safesession
  1. Create a Supabase server client and initialize AuthManager:
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";
import { AuthManager } from "supabase-safesession";

export function createSupabaseServerClient() {
  const cookieStore = cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value, ...options });
          } catch (error) {
            console.error("Error setting cookie in server component:", error);
          }
        },
        remove(name: string, options: CookieOptions) {
          try {
            cookieStore.delete({ name, ...options });
          } catch (error) {
            console.error("Error removing cookie in server component:", error);
          }
        },
      },
    }
  );
}
// Export the initialized Supabase client and AuthManager
export const supabaseServerClient = () => createSupabaseServerClient();
export const supabaseServerAuth = () =>
  new AuthManager(supabaseServerClient(), process.env.SUPABASE_JWT_SECRET!);
  1. use AuthManager inside your server components:
const autoRefreshToken = true;

export default async function ExampleComponent() {
  // autoRefreshToken is optional with a default value of false
  const {
    data: session,
    status,
    error,
  } = await supabaseServerAuth.getSafeSession(autoRefreshToken);

  // Implement component logic using the session data
  return <div>User session status: {status}</div>;
}