Lightweight JWT Auth for Next.js
next-lite-auth is a lightweight, JWT-based authentication solution for Next.js applications, designed specifically for scenarios where a full database or third-party auth service is overkill. It uses static JSON for user management, loaded via environment variables, eliminating the need for database setup. The current stable version is 0.2.6. Release cadence appears to be iterative and feature-driven within the 0.x range, indicating active development. Its primary differentiators are its zero-database approach, ease of setup, and a built-in login UI, making it suitable for MVPs, internal tools, demos, and educational projects. It explicitly states it is not recommended for production environments requiring robust security or scalability, instead catering to rapid development and OSS projects where authentication can be easily toggled via environment variables.
Common errors
-
Error: `createLiteAuth` must be called with a `jwtSecret`.
cause The `jwtSecret` property was missing or undefined when calling `createLiteAuth`.fixEnsure `process.env.LITE_AUTH_SECRET` is set in your `.env.local` file and accessible in the environment where `createLiteAuth` is called. For development, a fallback might be acceptable, but avoid in production. -
Error: `LiteAuthProvider` is a client component and cannot be rendered directly in a Server Component without 'use client'.
cause Attempting to import `LiteAuthProvider` directly from `next-lite-auth` into a Server Component or not wrapping it in a client component.fixImport `LiteAuthProvider` from `next-lite-auth/client` and ensure it is used within a component marked with `'use client'`, as shown in the quickstart example of `components/auth-provider.tsx`. -
TypeError: Cannot read properties of undefined (reading 'email') when accessing user data.
cause The `user` object returned by `useLiteAuth` or `getUserFromCookies` is `null` or `undefined`, indicating no user is logged in.fixAlways check if `user` is truthy before attempting to access its properties (e.g., `if (user) { console.log(user.email); }`). Handle the case where no user is logged in gracefully. -
Error: Invalid JSON in LITE_AUTH_USERS environment variable.
cause The `LITE_AUTH_USERS` environment variable contains malformed JSON, preventing `usersFromEnv()` from parsing it correctly.fixVerify that the `LITE_AUTH_USERS` environment variable is a valid JSON string representing an array of user objects, for example: `[{"email":"test@example.com","password":"pass"}]`.
Warnings
- gotcha next-lite-auth is explicitly stated as 'Not for production'. It is designed for demos, OSS projects, internal tools, and quick Vercel deployments. It may lack the robust security, scalability, and feature set required for public-facing production applications.
- breaking The `LiteAuthProvider` component and `useLiteAuth` hook must be imported from `next-lite-auth/client`. Importing directly from `next-lite-auth` will cause errors in client components due to missing 'use client' directive.
- gotcha User data is stored directly in environment variables (LITE_AUTH_USERS) as a JSON string. This approach is not suitable for large numbers of users or dynamic user management and could pose security risks if `.env.local` files are not properly secured.
- gotcha The `jwtSecret` is a critical security component. Using a hardcoded or easily guessable secret, or allowing a fallback like `fallback-secret-for-dev` in a non-development environment, significantly compromises the security of the JWTs.
Install
-
npm install next-lite-auth -
yarn add next-lite-auth -
pnpm add next-lite-auth
Imports
- createLiteAuth
const { createLiteAuth } = require('next-lite-auth');import { createLiteAuth } from 'next-lite-auth'; - usersFromEnv
const { usersFromEnv } = require('next-lite-auth');import { usersFromEnv } from 'next-lite-auth'; - LiteAuthProvider
import { LiteAuthProvider } from 'next-lite-auth';import { LiteAuthProvider } from 'next-lite-auth/client'; - useLiteAuth
import { useLiteAuth } from 'next-lite-auth';import { useLiteAuth } from 'next-lite-auth/client'; - handlers
import { handlers } from 'next-lite-auth';import { handlers } from '@/auth'; - middleware
import { middleware } from 'next-lite-auth';import { middleware } from '@/auth';
Quickstart
import { createLiteAuth, usersFromEnv } from "next-lite-auth";
import { LiteAuthProvider } from "next-lite-auth/client";
import { cookies } from 'next/headers';
// --- 1. Create auth.ts at your project root ---
// auth.ts (server-side)
export const { handlers, middleware, getUserFromCookies } = createLiteAuth({
users: usersFromEnv(),
jwtSecret: process.env.LITE_AUTH_SECRET ?? 'fallback-secret-for-dev',
enabled: process.env.LITE_AUTH_ENABLED !== "false",
});
// .env.local example
// LITE_AUTH_SECRET=your-random-secret-here
// LITE_AUTH_ENABLED=true
// LITE_AUTH_USERS=[{"email":"admin@example.com","password":"secret","role":"admin","name":"Admin"}]
// --- 2. Add one route file ---
// app/api/auth/[...liteauth]/route.ts (API Route)
// import { handlers } from "@/auth"; // Assuming '@/auth' resolves to the auth.ts file
// export const { GET, POST } = handlers;
// --- 3. Wrap root layout ---
// components/auth-provider-wrapper.tsx (Client Component)
"use client";
export function AuthProvider({ children }: { children: React.ReactNode }) {
return (
<LiteAuthProvider protect={["/dashboard", "/settings"]} appName="My Next App">
{children}
</LiteAuthProvider>
);
}
// app/layout.tsx (Server Component)
// import { AuthProvider } from "@/components/auth-provider-wrapper";
// export default function RootLayout({ children }: { children: React.ReactNode }) {
// return (
// <html>
// <body>
// <AuthProvider>{children}</AuthProvider>
// </body>
// </html>
// );
// }
// Example of server-side usage outside middleware/API routes
async function getServerSideUser() {
const user = await getUserFromCookies(cookies());
console.log('Server-side user:', user?.email);
}
// Call the function (e.g., in a Server Component or route handler)
getServerSideUser();