A ready-to-use authentication template built with Next.js 14 and Auth.js (formerly NextAuth.js).
Important
The Resend email service requires a verified custom domain for emails to function properly in production.
You can access the demo here: https://nextjs-authjs-template.vercel.app/
- For testing purposes, use these credentials:
- Email: [email protected]
- Password: 123456
- π Complete Authentication System: Secure user registration and login.
- βοΈ Email Verification: Verify accounts through email confirmation.
- π Password Reset: Self-service password recovery.
- π Two-Factor Authentication (2FA): Optional additional security.
- π Social Login: Sign in using Google, Facebook, and GitHub.
- π€ User Roles: Differentiate between Admin and regular users.
- π‘οΈ Protected Routes: Secure pages accessible only to authenticated users.
- π± Responsive Design: Fully responsive UI for all devices.
- π§ Easy Customization: Modular structure for seamless modifications.
- Node.js: Version 18.17 or higher.
- Database: PostgreSQL.
- Resend API Key: For sending emails (ensure your custom domain is verified for production).
-
Clone the Repository
git clone https://github.com/viniciuspra/nextjs-authjs-template.git cd nextjs-authjs-template
-
Install Dependencies
Use your package manager of choice:
npm install # or yarn install # or pnpm install
-
Environment Setup
Copy the example environment file and update it with your configuration:
cp .env.example .env.local
Edit
.env.local
with your credentials and configuration values. -
Database Setup
Generate the Prisma client and migrate your database schema:
npx prisma generate npx prisma db push
-
Start the Development Server
Launch the app locally:
npm run dev
Visit http://localhost:3000 in your browser.
Variable | Purpose |
---|---|
NEXT_PUBLIC_APP_URL |
Base URL for your application |
DATABASE_URL |
PostgreSQL connection string |
AUTH_SECRET |
Secret for JWT encryption |
GOOGLE_CLIENT_ID |
Google OAuth Client ID |
GOOGLE_CLIENT_SECRET |
Google OAuth Client Secret |
FACEBOOK_CLIENT_ID |
Facebook OAuth Client ID |
FACEBOOK_CLIENT_SECRET |
Facebook OAuth Client Secret |
GITHUB_CLIENT_ID |
GitHub OAuth Client ID (optional) |
GITHUB_CLIENT_SECRET |
GitHub OAuth Client Secret (optional) |
RESEND_API_KEY |
API key for sending emails |
.
βββ prisma/ # Prisma folder (Database schema and migrations)
βββ public/ # Public assets (Static files like images, fonts, etc.)
βββ src/ # Source code folder
β βββ actions/ # Next.js API actions
β βββ app/ # Next.js App Router components
β β βββ api/ # API routes
β β βββ (protected)/ # Protected routes (accessible only by authenticated users)
β β βββ auth/ # Authentication pages
β βββ components/ # Reusable React components
β βββ email-template.tsx # Email verification template
β βββ password-reset-email-template.tsx # Password reset template
β βββ two-factor-email-template.tsx # 2FA code template
β βββ data/ # Database queries and data access layer
β β βββ account.ts # Account data access (OAuth accounts)
β β βββ password-reset-token.ts # Password reset tokens
β β βββ two-factor-confirmation.ts # Two-factor confirmation data
β β βββ two-factor-token.ts # Two-factor tokens
β β βββ user.ts # User data access
β β βββ verification-token.ts # Email verification tokens
β βββ hooks/ # Custom React hooks
β β βββ use-current-role.ts # Hook to retrieve current user role
β β βββ use-current-user.ts # Hook to retrieve current user info
β βββ lib/ # Utility libraries and helpers
β β βββ auth.ts # Auth-related utility functions
β β βββ mail.ts # Email sending utilities
β β βββ token.ts # Token generation utilities
β βββ routes/ # Route definitions
β βββ schemas/ # Zod schemas for form validation
β βββ auth.config.ts # Authentication configuration for OAuth providers
β βββ middleware.ts # Middleware for authentication
- Registration: Users create an account using email and password.
- Email Verification: Confirm registration via email link.
- Login: Authenticate using email/password or social login providers.
- Two-Factor Authentication (2FA): Optionally secure your account with 2FA.
- Password Reset: Allow users to reset forgotten passwords.
Edit auth.config.ts
to enable or add additional OAuth providers. Simply uncomment the existing providers or insert new ones following the provided format. For example, to add a provider for Twitter, you can add the following snippet:
// src/auth.config.ts
import TwitterProvider from "next-auth/providers/twitter";
export default {
providers: [
// Other providers...
TwitterProvider({
clientId: process.env.TWITTER_CLIENT_ID,
clientSecret: process.env.TWITTER_CLIENT_SECRET,
}),
],
// ...other configuration options
};
Note
For a full list of supported providers and additional configuration details, please refer to the Auth.js documentation.
You can customize your applicationβs routes by editing the routes.ts
file. This file defines which routes are public, which routes are authentication-related, and where to redirect users after a successful login.
For example, consider the following implementation:
- Public Routes: Accessible without authentication.
- Auth Routes: For login, registration, etc.
- Protected Routes: Accessible only to authenticated users.
- Default Redirects: Post-login redirection settings.
// src/routes/index.ts
const publicRoutes = ["/", "/auth/new-verification"];
const authRoutes = [
"/auth/login",
"/auth/register",
"/auth/error",
"/auth/forgot-password",
"/auth/new-password",
];
const apiAuthPrefix = "/api/auth";
const DEFAULT_LOGIN_REDIRECT = "/settings";
export { publicRoutes, authRoutes, apiAuthPrefix, DEFAULT_LOGIN_REDIRECT };
You can easily send custom emails using React Email components with Resend. Here's how to implement a new email in your app:
Create a new file inside the components/
folder (or a subfolder like components/emails/
) and name it something like welcome-email-template.tsx
.
This is your actual email layout and content. Use React Email to build it:
// components/welcome-email-template.tsx
import { Html, Body, Text, Container } from "@react-email/components";
export const WelcomeEmailTemplate = ({ name }: { name: string }) => {
return (
<Html>
<Body style={{ fontFamily: "Arial, sans-serif" }}>
<Container>
<Text>Hello {name},</Text>
<Text>Welcome to our app! π</Text>
<Text>Weβre excited to have you on board.</Text>
</Container>
</Body>
</Html>
);
};
export default WelcomeEmailTemplate;
Tip
You can add any structure and styling supported by @react-email/components.
Go to src/lib/mail.ts
and import your new template. Then, create a function to send it using Resend.
// lib/mail.ts
import { Resend } from "resend";
import WelcomeEmailTemplate from "@/components/welcome-email-template";
const resend = new Resend(process.env.RESEND_API_KEY);
/**
* Send a welcome email to the user
*
* @param email - Recipient email address
* @param name - User's name
*/
export const sendWelcomeEmail = async (email: string, name: string) => {
try {
const { data, error } = await resend.emails.send({
from: "YourApp <[email protected]>", // Your verified Resend domain or use `[email protected]>` in development
to: email,
subject: "Welcome to Our App!",
react: WelcomeEmailTemplate({ name }),
});
if (error) {
throw new Error(error.message);
}
return data;
} catch (err) {
console.error("Failed to send welcome email:", err);
}
};
Note
You can adjust the props passed to your template depending on what content your email needs.
This template uses Prisma with PostgreSQL. The schema defines:
- User: Core user information.
- Account: OAuth account associations.
- VerificationToken: Tokens for email verification.
- PasswordResetToken: Tokens for password recovery.
- TwoFactorToken: Codes for 2FA.
- TwoFactorConfirmation: Confirmations for 2FA.
Deploy your application on any platform that supports Next.js (e.g., Vercel, Railway). Remember: Set all environment variables on your deployment platform for smooth operation.
If you find this template helpful, please give it a star on GitHub and consider contributing. For any issues or suggestions, open an issue in the repository.