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 {  } from 'permix'

const  = <{
  : {
    : { : boolean }
    : 'create' | 'read'
  }
}>()

// Set up initial permissions
.({
  : {
    : true,
    :  => !!?.
  }
})

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

// Later, hydrate permissions from the 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  from 'express'
import {  } from 'permix'

const  = ()
const  = <{
  : {
    : 'create' | 'read'
  }
}>()

.('/', (, ) => {
  // Setup permissions on the server
  .({
    : {
      : true,
      : true
    }
  })

  // Dehydrate permissions for client
  const  = .()

  // Send HTML with embedded permissions data
  .(`
    <!DOCTYPE html>
    <html>
      <head>
        <script>
          window.__INITIAL_PERMISSIONS__ = ${.()};
        </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>
  `)
})