NuxtHub Core

repository·main·Indexed 23 days ago

https://github.com/nuxt-hub/core

A full-stack development platform for Nuxt that simplifies building and deploying applications with integrated services including SQL databases, file storage, caching, and key-value stores. It includes a comprehensive CLI for database management, providing commands to generate, apply, squash, and mark migrations, as well as execute raw SQL queries and manage database tables.

Tokens
41.6K
Snippets
143
Records
220
Agent score
79%

What's inside @nuxthub/core

  1. What is NuxtHub?

    main

    NuxtHub is a platform designed to provide a complete backend experience for full-stack Nuxt applications. It is built to be widely compatible with various cloud providers by leveraging agnostic technologies such as Nuxt, Nitro, unstorage, and db0.

    NuxtHub offers several optional features for building full-stack applications:

    • SQL database: For storing application data.
    • Blob: For storing static assets like images and videos.
    • Cache: A caching system for Nuxt pages, API routes, or server functions.
    • Key-Value: A key-value store for accessible JSON data.
  2. Overview of NuxtHub features

    main

    NuxtHub is a platform designed to build and deploy full-stack Nuxt applications. It provides several optional features to extend your application's capabilities:

    • SQL database: Store application data with support for automatic migrations.
    • Files storage: Store static assets like images and videos.
    • Caching system: Cache Nuxt pages, API routes, or server functions to improve performance.
    • Key-Value (KV): Store JSON data that is accessible globally with low latency.
  3. Understand NuxtHub environment types

    main

    NuxtHub uses isolated environments to separate resources like databases, KV stores, and buckets. This prevents development or testing activities from affecting live production data.

    EnvironmentPurposeTrigger
    ProductionLive application serving end usersPush to main branch
    PreviewTesting pull requests and feature branchesPush to non-main branches
    StagingPre-production testing environmentNamed environment in configuration
    LocalDevelopment on your machineRunning nuxt dev
  4. Set up NuxtHub in a Monorepo (GitHub)

    main

    To deploy multiple applications from the same repository:

    1. When linking the repository, set the "project root directory" to the base folder of the specific Nuxt application.
    2. For additional projects linked to the same repository, the generated workflow will be named nuxthub-<projectSlug>.yml.
    3. Important: You must specify the project-key input parameter in the GitHub Action for each project to ensure it deploys to the correct NuxtHub project.
  5. Choose between Cache and KV storage

    main

    NuxtHub provides two distinct storage types. Choosing the right one depends on whether your data needs to expire automatically or persist indefinitely.

    Use Cache when:

    • You need TTL-based expiration (data expires after a set duration).
    • You are performing Response caching for API routes.
    • You are caching Computed data that can be recomputed if invalidated.
    • You want automatic cleanup of expired entries.

    Use KV when:

    • You need Persistent data that must not expire automatically.
    • You are managing User sessions or authentication tokens.
    • You are storing Application state like feature flags or configuration.
    • You are managing Counters for rate limiting or analytics.

    General Rule: Use Cache for data that can be recomputed, and use KV for data that must persist.

  6. Database connection detection via environment variables

    main

    NuxtHub automatically detects your database connection based on the following environment variables:

    PostgreSQL

    • Local/Embedded: Uses PGlite if no environment variables are set.
    • Standard: Uses postgres-js if DATABASE_URL, POSTGRES_URL, or POSTGRESQL_URL is set.
    • Neon: Use the neon-http driver with @neondatabase/serverless for Neon serverless PostgreSQL.

    MySQL

    • Uses mysql2 driver if DATABASE_URL or MYSQL_URL is set. (No local fallback available).

    SQLite

    • Turso: Uses libsql driver if TURSO_DATABASE_URL and TURSO_AUTH_TOKEN are set.
    • Local: Uses libsql locally with a file at .data/db/sqlite.db if no environment variables are set.
    • Cloudflare D1: Configure the database ID in nuxt.config.ts to allow NuxtHub to auto-generate wrangler bindings.
  7. Automatic migration behavior and configuration

    main

    Migrations are automatically applied when you run npx nuxt dev or npx nuxt build. Applied migrations are tracked in the _hub_migrations table.

    Important for Cloudflare D1: Migrations cannot run during the build process in CI because there is no database connection. You must run npx nuxt db migrate locally or as a dedicated CI step before deployment.

    You can disable automatic migrations in your nuxt.config.ts using applyMigrationsDuringBuild or applyMigrationsDuringDev.

    export default defineNuxtConfig({
      hub: {
        db: {
          applyMigrationsDuringBuild: false,
          applyMigrationsDuringDev: false
        }
      }
    })
  8. Understand and handle cache key normalization

    main

    Nitro automatically normalizes cache keys by removing non-alphanumeric characters (like / and -). This ensures compatibility with various storage backends and prevents path traversal vulnerabilities.

    Example of normalization: getKey: () => '/api/products/sale-items' becomes api/productssaleitems.json.

    Manual Invalidation Tip: When invalidating cache manually using a path or ID, you must reproduce this normalization. It is recommended to use a utility like escapeKey to ensure your manual key matches the internal one.

    // Recommended utility to reproduce Nitro's normalization
    function escapeKey(key: string | string[]) {
      return String(key).replace(/\W/g, "");
    }
    
    // Usage example for invalidation
    const normalizedKey = escapeKey('product/123/details')
    await useStorage('cache').removeItem(`nitro:functions:getProductDetails:${normalizedKey}.json`)
  9. Concept: Multipart Uploads for large files

    main

    Multipart uploads are used for large files (typically > 10MB) to improve reliability and allow for progress tracking by splitting the file into smaller chunks.

    This process involves several stages handled by the handleMultipartUpload server function:

    1. Create: Initializes the upload and returns an uploadId.
    2. Upload: Sends individual parts to the server.
    3. Complete: Finalizes the upload once all parts are received.
    4. Abort: Cancels the upload process.

    This mechanism is supported by Cloudflare R2, S3, Vercel Blob, and filesystem drivers.

  10. Manage Cloudflare Environments and Bindings

    main

    NuxtHub resolves the target environment using the CLOUDFLARE_ENV environment variable. If set, it merges environment-specific configuration from wrangler.jsonc and generates .output/server/wrangler.json with the resolved bindings.

    Important: The following bindings do not inherit from the top-level configuration and must be explicitly specified in each environment within wrangler.jsonc:

    • d1_databases
    • kv_namespaces
    • r2_buckets
    • vars (Environment variables)
    • durable_objects
    • services
  11. Deploy to Cloudflare preview or staging environments

    main

    To deploy to a specific named environment in Cloudflare, set the CLOUDFLARE_ENV environment variable during the nuxt build process.

    If CLOUDFLARE_ENV is unset, the build defaults to the production environment.

    # Deploy to the preview environment
    CLOUDFLARE_ENV=preview nuxt build
    
    # Deploy to the staging environment
    CLOUDFLARE_ENV=staging nuxt build