1.0.0 • Published 8 months ago

@fatal3rr/nextmagicauth v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

Next.js Passwordless Authentication

A simple, reusable module for implementing passwordless authentication in Next.js applications using Resend and NextAuth.js.

Features

  • Passwordless authentication using magic links
  • Email sending via Resend
  • Built with Next.js 14, NextAuth.js 5, and Prisma
  • TypeScript support
  • Tailwind CSS styling included
  • Simple, clean UI components

Installation

npm install @yourusername/next-passwordless-auth

Prerequisites

  1. Set up a Resend account and get your API key
  2. Set up a Prisma database with the required schema
  3. Configure your environment variables

Required Environment Variables

NEXTAUTH_URL=http://localhost:3000
AUTH_SECRET=your-auth-secret
RESEND_API_KEY=your-resend-api-key
EMAIL_FROM=your-verified-email@domain.com

Prisma Schema

Add these models to your Prisma schema:

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String?
  access_token      String?
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String?
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Usage

  1. Set up your auth configuration:
// src/auth.ts
import { createAuthConfig } from "@yourusername/next-passwordless-auth";
import prisma from "./lib/prisma";
import NextAuth from "next-auth";

const authConfig = createAuthConfig(prisma, {
  emailFrom: process.env.EMAIL_FROM!,
  resendApiKey: process.env.RESEND_API_KEY!,
  authSecret: process.env.AUTH_SECRET!,
  nextAuthUrl: process.env.NEXTAUTH_URL!,
});

export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);
  1. Wrap your app with the AuthProvider:
// src/app/layout.tsx
import { AuthProvider } from '@yourusername/next-passwordless-auth';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <AuthProvider>{children}</AuthProvider>
      </body>
    </html>
  );
}
  1. Use the LoginForm component:
// src/app/login/page.tsx
import { LoginForm } from '@yourusername/next-passwordless-auth';

export default function LoginPage() {
    return (
        <div className="flex min-h-screen items-center justify-center">
            <LoginForm />
        </div>
    );
}
  1. Set up the API route:
// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";

export const { GET, POST } = handlers;

Protected Routes

You can protect routes using the auth function:

// src/app/protected/page.tsx
import { auth } from "@/auth";

export default async function ProtectedPage() {
    const session = await auth();

    if (!session) {
        redirect("/login");
    }

    return (
        <div>
            <h1>Protected Page</h1>
            <p>Welcome {session.user?.email}</p>
        </div>
    );
}

Customization

The module exports TypeScript types and interfaces that you can use to customize the behavior:

import type {
  AuthModuleConfig,
  DEFAULT_STATE,
} from "@yourusername/next-passwordless-auth";

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1.0.0

8 months ago