guard() hook

Environment: server (configurable).

The guard() hook enables you to protect pages from unauthorized and unexpected access.

// /pages/admin/+guard.js
import { render } from 'vike/abort'
// This guard() hook protects all pages /pages/admin/**/+Page.js
export async function guard(pageContext) {
  if (!pageContext.user.isAdmin) {
    throw render(401, "You aren't allowed to access this page.')

Note that:

Execution order

The guard() hook is the first hook called after the routing is evaluated. It's always called before the data() hook. See API > Hooks > Order.

We generally recommend using throw render() / throw redirect() before fetching data: unauthorized and unexpected data fetching can be problematic.

If you want to guard your pages after or during fetching data, then use throw render() / throw redirect() inside your data() hook (or another Vike hook).

For being able to use throw render() / throw redirect() inside UI components, see #1707: Use throw render() / throw redirect() inside React/Vue/Solid components.


The guard() hook is called in the same environment as data(). In other words, it's always called on the server-side unless you configure data() to run on the client-side.

If the page doesn't have any data() hook, then guard() executes in the environment where the routing is evaluated. See API > Hooks > Order.

For more control on where and when your guarding logic is executed, consider using throw render() / throw redirect() inside another hook than guard().


export { guard }
import type { GuardAsync } from 'vike/types'
import { render } from 'vike/abort'
const guard: GuardAsync = async (pageContext): ReturnType<GuardAsync> => {
  // ...

See also