Superflare Documentation

website·Indexed 32 days ago

https://superflare.dev

An experimental full-stack toolkit for Cloudflare Workers. Superflare provides a relational ORM for D1, R2 file storage integration, session management, authentication, event broadcasting, asynchronous queues, and a CLI for migrations and seeding.

Tokens
10.3K
Snippets
74
Records
91
Agent score
63%

What's inside Superflare

  1. Overview of Superflare CLI

    The Superflare CLI is a development tool used to build local Superflare applications. It acts as a wrapper around the Wrangler CLI while providing additional functionality for database migrations, scaffolding, and environment synchronization.
    npx superflare
  2. Overview of Superflare full-stack toolkit

    Superflare is a full-stack toolkit (not a framework) that provides a layer of abstraction over Cloudflare's platform primitives. It is designed to be used alongside existing frameworks such as Remix, Next.js, or Nuxt.js, handling the 'glue' between the framework and Cloudflare services. It specifically leverages the following Cloudflare primitives:

    • D1: Relational database
    • R2: Object storage
    • Queues: Message queuing
    • Durable Objects: Real-time state management
    • Scheduled Workers: Recurring jobs
  3. Seed a local database with Superflare

    Superflare allows you to populate your local database with test data using a seed.ts file located in the project's db folder. This is useful for rapid iteration on the user interface and application logic during local development.
  4. Manage user sessions with SuperflareSession

    Superflare provides the SuperflareSession class to store user information across requests. It acts as a wrapper around a simple Session object and automatically tracks changes, committing them to the session store on the outgoing response.
  5. Implement temporary flash messages in sessions

    Flash messages are session entries that disappear after being read once. Use session.flash(key, value) to create a message and session.getFlash(key) to retrieve it.

    Important: You must use getFlash instead of get to read these messages; getFlash modifies the session to mark the message as read, and Superflare needs this modification to trigger the automatic commit to the session store on the outgoing response.

    // Setting a flash message in a loader
    export async function loader({ context: { session } }) {
      session.flash("success", "Your form was submitted successfully!");
      return json({ success: true });
    }
    
    // Reading a flash message in an action
    export async function action({ context: { session } }) {
      const success = session.getFlash("success");
      return json({ success });
    }
  6. Define a One-to-One relationship in Superflare

    A one-to-one relationship is defined using the hasOne method on the parent model and the belongsTo method on the child model. By default, Superflare assumes the foreign key on the related model is the name of the parent model followed by Id (e.g., userId). Related models are lazy-loaded by default; you can load them by awaiting the relation property or calling the relationship method.
    import { Model } from "superflare";
    import { Profile } from "./Profile";
    
    // Parent Model
    export class User extends Model {
      profile!: Profile | Promise<Profile>;
      $profile() {
        return this.hasOne(Profile);
      }
    }
    
    // Child Model
    export class Profile extends Model {
      user!: User | Promise<User>;
      $user() {
        return this.belongsTo(User);
      }
    }
    
    // Usage
    const user = await User.find(1);
    const profile = await user.profile; // Lazy loads and caches
  7. Stream large file uploads to R2

    To avoid loading large files entirely into memory (which happens when using request.formData()), use the parseMultipartFormData utility. This allows you to stream the file content directly to the R2 bucket.
    import { storage, parseMultipartFormData } from "superflare";
    
    export async function action({ request }) {
      const formData = await parseMultipartFormData(
        request,
        async ({ name, filename, stream, data }) => {
          if (name === "file") {
            const r2Object = await storage().put(filename, stream);
            return r2Object.key;
          }
          return data;
        }
      );
    
      const url = storage().url(formData.get("file"));
    }
  8. Verify a password against a Superflare hash

    To verify if a plain-text value matches a previously generated hash, use the hash().check() helper. This method returns a boolean indicating whether the value is correct.
    import { hash } from "superflare";
    
    const isCorrect = await hash().check("my-password", hashed);
  9. Prepare production database and secrets for Superflare deployment

    Before deploying your Superflare app to production, you must complete the following checklist to ensure the environment is correctly configured:

    1. Apply D1 Migrations: Run your database migrations against the production database using the --remote flag.
    2. Set Application Key: Configure the required APP_KEY secret in your production environment.
    # Apply D1 migrations to production
    npx wrangler d1 migrations apply <DB_NAME> --remote
    
    # Set the APP_KEY secret
    npx wrangler secret put APP_KEY
  10. Set up authentication in Superflare

    To enable authentication in a Superflare application, ensure the following requirements are met:

    1. Define a User model and create a corresponding users table in the database.
    2. Create an instance of SuperflareSession (automatically handled if using @superflare/remix).
    3. Create an instance of SuperflareAuth and provide it to your application code during requests (automatically handled if using @superflare/remix).
    4. Implement /register and /login routes for user access.
  11. Implement authentication with Superflare

    Superflare treats authentication as a core primitive rather than an add-on. Every new Superflare template includes a default User class and a corresponding users table migration to accelerate the setup of user management.
  12. Hash sensitive data with Superflare

    Superflare provides a hash() helper powered by bcrypt to securely hash passwords and other sensitive data. Use the make() method to generate a hash from a plain-text value.
    import { hash } from "superflare";
    
    const hashed = await hash().make("my-password");