Permix

Hydration (SSR)

Learn how to hydrate and dehydrate permissions in your application

Overview

Hydration is the process of converting server-side state into client-side state. In Permix, hydration allows you to serialize permissions on the server and restore them on the client.

Note that function-based permissions will be converted to false during dehydration since functions cannot be serialized to JSON. You should call setup method on the client side after hydration to fully restore function-based permissions.

Usage

Permix provides two instance methods for handling hydration:

  • dehydrate() - Converts the current permissions state into a JSON-serializable format
  • hydrate(state) - Restores permissions from a previously dehydrated state
import { createPermix } from 'permix'

const permix = createPermix<{
  post: {
    dataType: { isPublic: boolean }
    action: 'create' | 'read'
  }
}>()

// Set up initial permissions
permix.setup({
  post: {
    create: true,
    read: post => !!post?.isPublic
  }
})

// Dehydrate permissions to JSON
const state = permix.dehydrate()
// Result: { post: { create: true, read: false } }

// Later, hydrate permissions from the state
permix.hydrate(state)

Server-Side Rendering

Hydration is particularly useful in server-side rendering scenarios where you want to transfer permissions from the server to the client:

// Express server
import express from 'express'
import { createPermix } from 'permix'

const app = express()
const permix = createPermix<{
  post: {
    action: 'create' | 'read'
  }
}>()

app.get('/', (req, res) => {
  // Setup permissions on the server
  permix.setup({
    post: {
      create: true,
      read: true
    }
  })

  // Dehydrate permissions for client
  const dehydratedState = permix.dehydrate()

  // Send HTML with embedded permissions data
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <script>
          window.__INITIAL_PERMISSIONS__ = ${JSON.stringify(dehydratedState)};
        </script>
      </head>
      <body>
        <div id="app"></div>
        <script type="module">
          // Client-side code
          import { createPermix } from 'https://cdn.jsdelivr.net/npm/permix/+esm'

          const permix = createPermix();

          // Hydrate permissions from server data
          permix.hydrate(window.__INITIAL_PERMISSIONS__);

          // After hydration, you should call setup again
          // on the client side to fully restore function-based permissions
          permix.setup({
            post: {
              create: true,
              read: post => !!post?.isPublic
            }
          })
        </script>
      </body>
    </html>
  `)
})