Quickstart
Quickstart — Next.js
Add HelloJohn authentication to your Next.js app in 10 minutes. Middleware-based route protection, Server Components, and App Router support.
Time: ~10 minutes Prerequisites: A HelloJohn account (Cloud) or a self-hosted server running locally.
Install the SDK
npm install @hellojohn/nextjsyarn add @hellojohn/nextjspnpm add @hellojohn/nextjsSet environment variables
Create or update your .env.local file:
HELLOJOHN_PUBLISHABLE_KEY=pk_live_XXXXXXXXXXXXXXXX
HELLOJOHN_SECRET_KEY=sk_live_XXXXXXXXXXXXXXXXYour keys are available in the HelloJohn Dashboard under Clients.
Never expose your Secret Key in client-side code or commit it to version control. Only the Publishable Key (pk_...) is safe to use in the browser.
Add middleware
Create middleware.ts at the root of your project. This protects routes without any per-page code:
import { hellojohnMiddleware } from '@hellojohn/nextjs/middleware'
export default hellojohnMiddleware()
export const config = {
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
}Wrap your app with HelloJohnProvider
Add the provider to your root layout:
import { HelloJohnProvider } from '@hellojohn/nextjs'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<HelloJohnProvider>
{children}
</HelloJohnProvider>
</body>
</html>
)
}Add sign-in and sign-up pages
import { SignIn } from '@hellojohn/nextjs'
export default function SignInPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignIn />
</div>
)
}import { SignUp } from '@hellojohn/nextjs'
export default function SignUpPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignUp />
</div>
)
}Access the user in Server Components
import { auth } from '@hellojohn/nextjs/server'
import { redirect } from 'next/navigation'
export default async function DashboardPage() {
const { userId } = await auth()
if (!userId) {
redirect('/sign-in')
}
return <h1>Welcome to your dashboard</h1>
}Add a UserButton to your navbar
import { UserButton } from '@hellojohn/nextjs'
export function Navbar() {
return (
<nav className="flex items-center justify-between p-4">
<span className="font-semibold">My App</span>
<UserButton />
</nav>
)
}Verify it works
- Start your dev server:
npm run dev - Visit
/sign-in— you should see the HelloJohn sign-in form - Create an account and sign in
- Visit
/dashboard— unauthenticated users are redirected to/sign-in - When signed in, you should see the dashboard page