Guard

The guard() hook enables you to protect pages.

The most common use cases being authentication and authorization, see Guides > Authentication > Login flow.

Note that:

  • It's always used together with throw render() or throw redirect(). (The guard() hook doesn't accept any return value.)
  • It can be asynchronous. (Unlike Route Functions which are synchronous.)
  • A single guard() hook can apply to multiple pages. (By using the usual inheritance rules.)
export { guard }

import { render } from 'vike/abort'

async function guard(pageContext) {
  if (pageContext.urlPathname === '/hello/forbidden') {
    throw render(401, 'This page is forbidden.')
  }
}

TypeScript

export { guard }

import type { GuardAsync } from 'vike/types'
import { render } from 'vike/abort'

const guard: GuardAsync = async (pageContext): ReturnType<GuardAsync> => {
  if (pageContext.urlPathname === '/hello/forbidden') {
    throw render(401, 'This page is forbidden.')
  }
}