⚠
vite-plugin-ssr has been renamed Vike, see migration guide.

_error.page.js

The error page, which is defined by /renderer/_error.page.tsx, is rendered when an error occurs. It's also rendered when you call throw render(abortStatusCode).

// /renderer/_error.page.ts

export { Page }

import { usePageContext } from 'vike-react/usePageContext'
/* Or:
import { usePageContext } from 'vike-vue/usePageContext'
import { usePageContext } from 'vike-solid/usePageContext'
*/

function Page() {
  const pageContext = usePageContext()

  let msg: string // Message shown to the user
  const { abortReason, abortStatusCode } = pageContext
  if (abortReason?.notAdmin) {
    // Handle `throw render(403, { notAdmin: true })`
    msg = "You cannot access this page because you aren't an administrator."
  } else if (typeof abortReason === 'string') {
    // Handle `throw render(abortStatusCode, `You cannot access ${someCustomMessage}`)`
    msg = abortReason
  } else if (abortStatusCode === 403) {
    // Handle `throw render(403)`
    msg = "You cannot access this page because you don't have enough privileges."
  } else if (abortStatusCode === 401) {
    // Handle `throw render(401)`
    msg = "You cannot access this page because you aren't logged in. Please log in."
  } else {
    // Fallback error message
    msg = pageContext.is404 ?
      "This page doesn't exist." :
      "Something went wrong. Sincere apologies. Try again (later)."
  }

  return <p>{msg}</p>
}

// If you use TypeScript, you can define the type of `abortReason`
declare global {
  namespace Vike {
    interface PageContext {
      abortReason?:
        | string
        | { notAdmin: true }
    }
  }
}

namespace Vike refers to Vike which is the upcoming new name of vite-plugin-ssr, see #736.

The usePageContext() UI component hook allows you to access pageContext from any UI component.

The pageContext.abortReason and pageContext.abortStatusCode values are set by throw render(abortStatusCode, abortReason), and pageContext.is404 is set by vite-pugin-ssr.

The error page is rendered if:

  1. The URL didn't match the route of any of your pages (404 Page Not Found).
  2. One of your hooks threw an error (500 Internal Error).
  3. You called throw render(abortStatusCode).

The error page is also rendered when vite-plugin-ssr throws an unexpected error (it has a bug), but since vite-plugin-ssr has no known bug this is very rare.

Pre-rendering

If you use pre-rendering, then vite-plugin-ssr uses _error.page.js to generate /dist/client/404.html.

Most Static Hosts follow the convention of using the file 404.html as 404 page.