Integration Guide
NextJS
Quick Setup

Quick Setup for using auth² for Next.js Apps

1. Install the package

pnpm add @akarigar/auth
# or
npm install @akarigar/auth
# or
yarn add @akarigar/auth

2. Add environment variables

Add the following to your .env.local file:

NEXT_PUBLIC_AUTH_API_KEY=<your-auth²-api-key-here>
AUTH_SECRET_KEY=<your-auth²-api-key-here>

You can find/create these keys on the auth² dashboard (opens in a new tab).

3. Setup your middleware

Create /app/middleware.ts (must be in the same folder as your /app/ directory):

import { authMiddleware } from '@akarigar/auth';
 
export const middleware = authMiddleware();
 
export const config = {
  matcher: [
    /*
     * Match all routes you want to have auth² on.
     * Example: match all except API, static, image, favicon.
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

Advanced: Custom middleware logic

import { authMiddleware, createRouteMatcher } from '@akarigar/auth';
import { NextResponse } from 'next/server';
 
const isProtectedRoute = createRouteMatcher('/dashboard', '/profile/:path*');
 
export const middleware = authMiddleware((auth, request) => {
  // Rewrite / to /dashboard if authenticated
  if (auth.isAuthenticated && request.nextUrl.pathname === '/') {
    return NextResponse.rewrite(new URL('/dashboard', request.url));
  }
 
  // Only allow signed in users to protected routes
  if (isProtectedRoute(request)) {
    auth.ensureAuthenticated();
  }
});

4. Create sign-in and sign-up pages

/app/sign-in/[[...sign-in]]/page.tsx

import { SignIn } from '@akarigar/auth';
 
export default function SignInPage() {
  return <SignIn signUpUrl="/sign-up" />;
}

/app/sign-up/[[...sign-up]]/page.tsx

import { SignUp } from '@akarigar/auth';
 
export default function SignUpPage() {
  return <SignUp signInUrl="/sign-in" />;
}

5. Wrap your app with AuthProvider

In your root layout.tsx (server component):

import { AuthProvider } from '@akarigar/auth';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider>
      <html>
        <body>{children}</body>
      </html>
    </AuthProvider>
  );
}

That sets up auth² in 5 easy steps.