@nuxthq/neo

0.5.0 • Public • Published

Nuxt Neo

The Nuxt Toolkit to create full-stack applications on the Edge.

⚠️ this is a work in progress, not ready for production yet, the layer is going to be changed to a module very soon.

Features

  • Session management with secured & sealed cookie sessions
  • Helpers for OAuth support (GitHub, more soon)
  • Helpers to validate request body, query and params
  • Backed in database with SQLite
  • Create and query typed collections with useDB()
  • Access key-value storage with useKV()
  • Store files with useFiles()

Nuxt Neo leverages SQLite in development and uses D1 or Turso in production.

Setup

pnpm i -D @nuxthq/neo

Add it to your nuxt.config.ts:

export default defineNuxtConfig({
  extends: '@nuxthq/neo'
})

Next, add a NUXT_SESSION_PASSWORD env variable with at least 32 characters in the .env.

# .env
NUXT_SESSION_PASSWORD=password-with-at-least-32-characters

Nuxt Neo can generate one for you when running Nuxt in development the first time when no NUXT_SESSION_PASSWORD is set.

Lastly, Nuxt Neo will create a .data/ directory to store the sqlite database, KV and files. If you don't want to keep the same data between each developers, add the .data/ directory to the .gitignore:

node_modules
.nuxt
.output
.env
dist
.data

Vue Composables

Nuxt Neo automatically add some plugins to fetch the current user session to let you access it from your Vue components.

User Session

<script setup>
const { loggedIn, user, session, clear } = useUserSession()
</script>

<template>
  <div v-if="loggedIn">
    <h1>Welcome {{ user.login }}!</h1>
    <p>Logged in since {{ session.loggedInAt }}</p>
    <button @click="clear">Logout</button>
  </div>
  <div v-else>
    <h1>Not logged in</h1>
    <a href="/api/auth/github">Login with GitHub</a>
  </div>
</template>

Server Utils

Session Management

// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call
// Only store the data that allow you to recognize an user, but do not store sensitive data
await setUserSession(event, {
  user: {
    // ... user data
  },
  loggedInAt: new Date()
  // Any extra fields
})

// Get the current user session
const session = await getUserSession(event)

// Clear the current user session
await clearUserSession(event)

// Require a user session (send back 401 if no `user` key in session)
const session = await requireUserSession(event)

Validation Helpers

Neo exports 3 helpers to validate the request body, query and params.

The validation schema is based on Zod and h3-zod.

We export the z instance to let you create your own schemas without the need to import it.

It also add boolAsString, checkboxAsString, intAsString and numAsString to the z instance to let you validate string values that are actually numbers or booleans, learn more.

// Validate the request body
const body = await validateBody(event, {
  title: z.string().min(1)
})

// Validate the request query
const query = await validateQuery(event, {
  price: z.numAsString
})

// Validate the request params
const params = await validateParams(event, {
  id: z.intAsString
})

Database Helpers (SQLite)

// Returns a Drizzle instance
const db = useDB()

// All tables defined in `~/server/db/tables.ts`
tables.*

Example

Table definition in ~/server/db/tables.ts

import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'

export const todos = sqliteTable('todos', {
  id: integer('id').primaryKey(),
  userId: integer('user_id').notNull(), // GitHub Id
  title: text('title').notNull(),
  completed: integer('completed').notNull().default(0),
  createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
})

Learn more about Drizzle SQLite

API route to list all todos for the current user in ~/server/api/todos.get.ts

import { eq } from 'drizzle-orm'

export default eventHandler(async (event) => {
  const session = await requireUserSession(event)

  // List todos for the current user
  return await useDB()
    .select()
    .from(tables.todos)
    .where(eq(tables.todos.userId, session.user.id))
    .all()
})

Key-Value Store

const store = useKV(prefix?: string)

await store.getKeys()
await store.setItem(key, value)
await store.getItem(key, value)
await store.removeItem(key, value)
// Read more on all available methods on https://unstorage.unjs.io

OAuth Event Handlers

All helpers are exposed from the oauth global variable and can be used in your server routes or API routes.

The pattern is oauth.<provider>EventHandler({ onSuccess, config?, onError? }), example: oauth.githubEventHandler.

The helper returns an event handler that automatically redirects to the provider authorization page and then call onSuccess or onError depending on the result.

The config can be defined directly from the runtimeConfig in your nuxt.config.ts:

export default defineNuxtConfig({
  runtimeConfig: {
    oauth: {
      <provider>: {
        clientId: '...',
        clientSecret: '...'
      }
    }
  }
})

It can also be set using environment variables:

  • NUXT_OAUTH_<PROVIDER>_CLIENT_ID
  • NUXT_OAUTH_<PROVIDER>_CLIENT_SECRET

Supported providers:

  • GitHub
  • Spotify

Example

Example: ~/server/routes/auth/github.get.ts

export default oauth.githubEventHandler({
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, { user })
    return sendRedirect(event, '/')
  },
  // Optional, will return a json error and 401 status code by default
  onError(event, error) {
    console.error('GitHub OAuth error:', error)
    return sendRedirect(event, '/')
  },
})

Make sure to set the callback URL in your OAuth app settings as <your-domain>/auth/github.

Deploy

useDB():

  • DB environment variable with D1 binding or TURSO_DB_URL + TURSO_DB_TOKEN to connect with Turso database

useKV():

  • KV environment variable with CloudFlare KV binding

useFiles():

  • FILES environment variable with CloudFlare R2 binding (default bucket)
  • FILES_{BUCKET} environment variable with CloudFlare R2 binding for specific bucket (ex: FILES_AVATARS for useFiles('avatars'))

Readme

Keywords

none

Package Sidebar

Install

npm i @nuxthq/neo

Weekly Downloads

104

Version

0.5.0

License

UNLICENSED

Unpacked Size

43 kB

Total Files

56

Last publish

Collaborators

  • pi0
  • antfu
  • flosciante
  • farnabaz
  • atinux
  • benjamincanac
  • smarroufin
  • danielroe
  • larbish