protected$

API for the protected$ function

The protected$ function is used to define a protected page, meaning that only logged in user will be able to see the content in this page.

For instance:

In this page, if you are not lgoged in you will be redirected to the login page.

import { protected$ } from '@solid-mediakit/auth'

export default protected$((session$) => {
  return (
    <main>
      <h1>Protected Route</h1>
      <h1>hello {session$.user?.name}</h1>
    </main>
  )
}, '/login')

How to setup

First of all install the Mediakit Auth Plugin:

pnpm install @solid-mediakit/auth-plugin

Adding The Vite Plugin

import { authVite } from '@solid-mediakit/auth-plugin'
import { defineConfig } from '@solidjs/start/config'

export default defineConfig({
  ssr: true,
  vite: {
    plugins: [
      authVite({
        authOpts: {
          // the variable name of your authOptions (exported!!)
          name: 'authOptions',
          //   where your authOptions is located
          dir: '~/server/auth',
        },
        // where should we redirect when the user is not logged in
        redirectTo: '/login',
      }),
    ],
  },
})

This is it! you are good to go.

protected$ Usage

Types

export function protected$(
  page: (session$: Session) => JSXElement,
  fallBack: () => JSXElement
): VoidComponent
export function protected$(
  page: (session$: Session) => JSXElement,
  redirectTo?: string
): VoidComponent
export function protected$(...args: any[]): VoidComponent {
  throw new Error('Should be compiled by the auth plugin.')
}

that basically means, protected$ takes:

  • first argument: the page to be rendered if the user is logged in - required!
  • second argument: could be either a fallback function or a string to redirect to: so basically if you want to SSR redirect when the user is not logged in, pass in a redirect url, if you pass a fallback function, it will be rendered instead of the page if the user is not logged in. By default we will use the rediectTo url mentioned in the vite config so its optional.

Protected without fallback

This is basically being compiled to:

import { authOptions } from '~/server/auth'
import { Show } from 'solid-js'
import { getSession } from '@solid-mediakit/auth'
import { getRequestEvent } from 'solid-js/web'
import { createAsync } from '@solidjs/router'
import { redirect } from '@solidjs/router'
import { cache } from '@solidjs/router'
import { protected$ } from '@solid-mediakit/auth'

const _$$getUser = cache(async () => {
  'use server'

  const event = getRequestEvent()
  const session = await getSession(event.request, authOptions)
  if (!session) {
    throw redirect('/')
  }
  return session
}, 'media-user')

export default () => {
  const _$$session = createAsync(() => _$$getUser())
  const _$$RenderProtected = () => {
    return (
      <main>
        <h1>Protected Route</h1>
        <h1>hello {_$$session().user?.name}</h1>
      </main>
    )
  }
  return (
    <Show when={_$$session()?.user}>
      <_$$RenderProtected />
    </Show>
  )
}

Protected with fallback

import { protected$ } from '@solid-mediakit/auth'
import { protectedQuery } from '~/server/user/user.queries'

export default protected$(
  (session$) => {
    const res = protectedQuery(() => ({ hello: 'world' }))
    return (
      <div>
        <h1>Protected Page</h1>
        <p>Session: {JSON.stringify(session$)}</p>
        <p>Response: {JSON.stringify(res.data)}</p>
      </div>
    )
  },
  () => <div>Not logged in</div>
)

This is basically being compiled to:

import { Show } from 'solid-js'
import { getSession } from '@solid-mediakit/auth'
import { getRequestEvent } from 'solid-js/web'
import { createAsync } from '@solidjs/router'
import { cache } from '@solidjs/router'
import { protected$ } from '@solid-mediakit/auth'
import { protectedQuery } from '~/server/user/user.queries'

const _$$getUser = cache(async () => {
  'use server'

  const event = getRequestEvent()
  return await getSession(event.request, authOptions)
}, 'media-user')

export default () => {
  const _$$session = createAsync(() => _$$getUser())
  const _$$RenderFallBack = () => <div>Not logged in</div>
  const _$$RenderProtected = () => {
    const res = protectedQuery(() => ({
      hello: 'world',
    }))
    return (
      <div>
        <h1>Protected Page</h1>
        <p>Session: {JSON.stringify(_$$session())}</p>
        <p>Response: {JSON.stringify(res.data)}</p>
      </div>
    )
  }
  return (
    <Show when={_$$session()?.user} fallback={<_$$RenderFallBack />}>
      <_$$RenderProtected />
    </Show>
  )
}