Skip to main content
The @basictech/nextjs package includes middleware utilities to protect routes and require authentication before accessing certain pages.

Quick Setup

Create a middleware.ts file in your project root:
middleware.ts
With this setup:
  • Routes matching /dashboard/*, /settings/*, or /api/protected/* require authentication
  • Unauthenticated users are redirected to /login
  • The return URL is preserved so users can be redirected back after signing in

Configuration Options

createBasicMiddleware

The main function to create authentication middleware.

Options

Route Matching

Routes support simple glob patterns with * wildcard:

Alternative: Simple Auth Middleware

For simpler use cases, use withBasicAuth which applies default settings:
middleware.ts
This redirects unauthenticated users to /login for any matched routes.

Utility Functions

getAuthFromRequest

Check authentication status from a request:

getReturnUrl

Get the return URL from search params (useful on login pages):

Full Example

middleware.ts

Login Page Example

Create a login page that handles the return URL:
app/login/page.tsx