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

next-typed-action

v0.1.0

Published

Next.js Server Actions with fully type-safety using zod

Downloads

75

Readme

Table of Contents

Key Features

  • Easy to use: create action, provide Zod schema and use it :tada:
  • Protected actions: protect your actions with guards for auth/roles or any other logic
  • Provide context: provide the context using middlewares
  • Actions reusability: reuse action clients and attach middlewares to it to create new clients
  • Use with hooks: integrate with yor client form to show loading/validation error or refetch your data
  • Infer action type: infer action context and input type to use it for action handlers in different modules

Installation

Requirements

  • Next.js >= 12.4.x
  • TypeScript >= 5.x.x

Config next.config.js

module.exports = {
  experimental: {
    serverActions: true,
    // ...
  },
}

Setup

// src/lib/server-actions.ts
import { typedServerActionClient } from 'next-typed-action';
import { cookies } from "next/headers";

export const actionClient = typedServerActionClient()

export const authActionClient = actionClient.use((ctx) => {
  const userId = cookies().get('userId') // can access previous context value
  if (!userId) {
    throw new Error('Unauthorized') // protect action guard
  }
  return {
    userId, // context will be merged with previous context automatically
  }
})
// src/app/_actions.ts
'use server'

import { z } from 'zod';
import { authActionClient, actionClient } from '@/lib/serverActions'

const loginDto = z.object({
  username: z.string(),
  password: z.string(),
})
const login = actionClient
  .input(loginDto)
  .action(({ input, ctx }) => {
    // ...
  })

const createItem = authActionClient
  .input(z.string())
  .action(({ input, ctx }) => {
    // ...
  })

Run command

npm install next-typed-action zod

or

yard add next-typed-action zod

or

pnpm add next-typed-action zod

Usage

Multiple middlewares

import { typedServerActionClient } from 'next-typed-action';
const actionClient = typedServerActionClient()
const authActionClient = actionClient.use(() => {
  // ...
})
const adminActionClient = authActionClient.use(() => {
  // ...
})
const otherActionClient = adminActionClient
  .use(() => {
   // ...
  })
  .use(() => {
    // ...
  })
  .use()

Reuse action with input declare schema once and reuse

const itemOperationsActionClient = authActionClient.input(z.string())

const deleteItem = itemOperationsActionClient.action(({ input, ctx }) => {})
const getItem = itemOperationsActionClient.action(({ input, ctx }) => {})
const someActionItem = itemOperationsActionClient.action(({ input, ctx }) => {})

Create Action without input

const itemOperationsActionClient = authActionClient.action(
  ({ 
    input, // void type
    ctx 
  }) => {
    // ...
})

Usage with form

'use client'
import { useFormAction } from "next-typed-action";
import { login } from './_actions'

export default LoginForm()
{
  const { validation, isLoading, error } = useFormAction(login)
  
  return (
    <form action={onSubmit}>
      <input name="username"/>
      // Show validation error type-safety way for each field in form
      {validation?.username && <div>{validation.username[0]}</div>

      <input name="password"/>
      {validation?.password && <div>{validation.password[0]}</div>
        
      <button type="submit" disabled={isLoading}>Create</button>
      // Show server error
      {error && <div>{error.message}</div>}
    </form>
  )
}

Usage inline without form submit

import { useFormAction } from "next-typed-action";
import { createItem } from './_actions'

export default CreateItemForm()
{
  return (
    <div>
      <button type="submit" onClick={async () => {
        const { error, data, validation, status } = await createItem({ name: 'mock-item' })
        // work with returned data
        if (status === 'success') {
          // ...
        } else if (status === 'validationError') {
          // ...
        } else if (status === 'error') {
          // ...
        }
      }}>
        Create
      </button>
    </div>
  )
}

Throw error to Boundary with throwable action

'use client'
import { useFormAction } from "next-typed-action";

const loginThrowable = actionClient
  .actionThrowable(({ input, ctx }) => {
    // ...
  })

export default LoginForm()
{
  // Throw error to boundary on server error
  // Validation error still will be handled by useFormAction
  const { validation, isLoading } = useFormAction(loginThrowable)
  
  return (
    <form action={onSubmit}>
      // ...
    </form>
  )
}

Throw error to Boundary in action client

import { useFormAction } from "next-typed-action";

const createItemThrowable = actionClient
  .input(...)
  .actionThrowable(({ input, ctx }) => {
    // ...
  })

export default CreateItemForm()
{
  return (
    <div>
      <button type="submit" onClick={async () => {
        const { data, validation, status } = await createItemThrowable(
          { name: 'mock-item' }, 
        )
      }}>
        Create
      </button>
    </div>
  )
}

Infer Action Context and Input

import { typedServerActionClient, inferContext, inferAction, inferInput } from 'next-typed-action';
const actionClient = typedServerActionClient()

type ActionClientContext = inferContext<typeof actionClient> // {}
type ActionClient = inferAction<typeof actionClient> // { ctx: {} }
const authActionClient = actionClient.use(() => ({
  userId: 'mock-user-id',
}))

type AuthActionClientContext = inferContext<typeof actionClient> // { userId: string }
type AuthActionClient = inferAction<typeof actionClient> // { ctx: { userId: string } }
const loginActionClient = authActionClient.input(z.object({
    username: z.string(),
    password: z.string(),
  }))

type LoginActionClientContext = inferContext<typeof actionClient> // { userId: string }
type LoginActionClientInput = inferInput<typeof actionClient> // { username: string, password: string }
type LoginActionClient = inferAction<typeof actionClient> // { ctx: { userId: string }, input: { username: string, password: string } }

API

useFormAction hook with default action

const {
  status: 'error' | 'validationError' | 'success' | 'idle',
  data: TData | undefined,
  error: string | undefined,
  validation: Record<keyof z.input<TSchema>, string[]> | undefined,
  isLoading: boolean,
  isError: boolean,
  isValidationError: boolean,
  isSuccess: boolean,
  submit: (schema: z.input<TShema> | FormData) => void,
  reset: () => void,
} = useFormAction<TSchema, TData>(
  typedServerAction: ClientServerActionSafe<TShema, TData>, // action created by typedServerActionClient().[...].action
)

useFormAction hook with throwable action

const {
  status: 'validationError' | 'success' | 'idle',
  data: TData | undefined,
  validation: Record<keyof z.input<TSchema>, string[]> | undefined,
  isLoading: boolean,
  isValidationError: boolean,
  isSuccess: boolean,
  submit: (schema: z.input<TShema> | FormData) => void,
  reset: () => void,
} = useFormAction<TSchema, TData>(
  typedServerAction: ClientServerActionThrowable<TShema, TData>, // action created by typedServerActionClient().[...].actionThrowable
)

Other

TODO

License

MIT