Skip to main content

Command Palette

Search for a command to run...

Next Auth with Next JS Typescript

Updated
2 min read
Next Auth with Next JS Typescript

Step install and setting

  1. Install Next Auth

  2. Create file with Next Auth


  1. Install Next Auth

Go to website : https://next-auth.js.org/getting-started/example

install with npm in project npm install next-auth


  1. Create file with Next Auth

Create file in “src/app/api/auth/[…nextauth]/route.ts

import NextAuth from "next-auth";
import { options } from "@/config/options";

const handler = NextAuth(options);
export { handler as GET, handler as POST };

Create “NEXTAUTH_SECRET” with npm in project npx auth secret and it will autogenerate a random value and put it in your .env.local file.

Create folder and file in “src“ create folder config and create file options.ts in folder “config”

import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { redirect } from "next/navigation";

export const options: NextAuthOptions = {
    providers: [
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                username: {
                    label: "Username:",
                    type: "text",
                    placeholder: "",
                },
                password: {
                    label: "Password:",
                    type: "password",
                    placeholder: "",
                },
            },
            async authorize(credentials) {
                const user = { id: "42", name: "Dave", password: "nextauth" }
                if (credentials?.username === user.name && credentials?.password === user.password) {
                    return user
                } else {
                    return null
                }
            },
        }),
    ],
};

Create file session-provider.tsx in folder “config“

"use client";
import { SessionProvider } from "next-auth/react";

export default function AuthProvider({
    children,
}: {
    children: React.ReactNode;
}) {
    return (
        <SessionProvider>
            {children}
        </SessionProvider>
    );
}

Edit “layout.tsx”

import AuthProvider from "@/config/session-provider";

export default function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <html lang="en">
            <body>
                <AuthProvider>{children}</AuthProvider>
            </body>
        </html>
    );
}

View All Docs : https://next-auth.js.org/getting-started/introduction