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

@nuxthq/neo

v0.5.0

Published

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

Downloads

459

Readme

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'))