Forem

Cover image for setting up next auth with the new app directory
Nelson chege
Nelson chege

Posted on • Edited on

14 1 1

setting up next auth with the new app directory

I was looking for ways to setup next-auth with the new app directory and found no blog that gave out the steps for actually doing it.

here are the steps of setting it up.

for this, i did not use the scr file structure in my next project.

i install next auth

npm install next-auth

ii add an api route

touch app/api/auth/[...nextauth]/route.ts

inside of the routes add the following code

import { authOptions } from "@/utils/authoptions";
import NextAuth from "next-auth/next";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
Enter fullscreen mode Exit fullscreen mode

This handle all requests related to next-auth.
we need to create authOptions

iii create authOptions

there are different providers that can be use for authentication,
you can have a look at the next-auth docs to view how to impliment for different providers
in this case ill simply use the credential provider

mkdir utils

touch authOptions.ts

inside the authOptions file ,add the following

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

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" },
      },
      authorize(credentials: any, req) {
        // database operations
        return {
          id: "1",
          Email: credentials.email,
        };
      },
    }),
  ],
};

Enter fullscreen mode Exit fullscreen mode

iv adding required environment variables

next auth needs the following environment variable

# this is for jwt encording
NEXTAUTH_SECRET='supersecretkey'

#used to specify the url to the site
NEXTAUTH_URL='http://localhost:3000'

Enter fullscreen mode Exit fullscreen mode

shifting to handling sessions in the client side

v creating a session provider

mkdir providers

touch SessionProvider.tsx

then add the following code

"use client";

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

type sessionProps = {
  children: React.ReactNode;
};
function NextAuthSessionProvider({ children }: sessionProps) {
  return <SessionProvider>{children}</SessionProvider>;
}

export default NextAuthSessionProvider;

Enter fullscreen mode Exit fullscreen mode

vi adding the provider to layout.tsx

include it to the rootLayout function


export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <NextAuthSessionProvider>{children}</NextAuthSessionProvider>
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

and thats it , you can use the usesession hook to check if someone is logged in or not.

here is a link to the full code https://github.com/nelsonchege/next-auth-with-app-directory

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay