πŸ”‘ Middleware

To perform checks on your page before rendering it to the client, follow these default steps. After reviewing this code, check out the Template section for an expanded discussion on middleware.


1. Import The Middleware

In your component file, import the Middleware component:

import Middleware from "src/components/middleware";

2. Wrap Your HTML

Wrap your page's HTML content inside the <Middleware> component:

export default function App() {
    return (
        <Middleware>
            // your html here
        </Middleware>
    )
}

3. Define Your Logic

Than in the src/functions/middlewareHandler.ts file you need to add the route and define your logic

//* here you can add your own route
//* return an object with the success key set to true if the user is allowed to access the route
//* return an object with the redirect key set to the path you want to redirect the user to if you want to redirect the user to a different page
//* return nothing if the user is not allowed to access the route and it will be send back to its previous page
//* if you dont add your page in here it will allow the user to access the page
import notify from "src/_components/notify";

export default function middlewareHandler({ location, location, searchParams, session }: { location: string, searchParams: Record<string, any>, session: Record<string, any> }) {
  switch (location) {
    case '/test':

      if (session?.email && session?.provider) { 
        return { success: true }; 
      }
      return { redirect: '/login' };

    case '/admin':

      if (session?.email && session?.provider && session?.admin === true) {
        return { success: true }; 
      } else if (!session?.email || !session?.provider) {
        return { redirect: '/login' };
      } else if (!session?.admin) { 
        notify.error('middleware.notAdmin');
      }
      return

    default:
      return { success: true };
  }
}

πŸ”‘ Return Values

  • success: true If you want the user to access the page, return this object.

  • redirect: '/path' If you want to redirect the user to another page, return this object. For example, use redirect: '/login' to send users to the login page.

  • null or undefined If you don't return anything, the user will be sent back to the last page they were on.


The session data of the user is provided so you can perform checks on there date (e.g there roles).

Last updated