setting up next-auth with the new app directory

Nelson Chege
2 min readJun 24, 2023

--

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

here are the steps for 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]/routes.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 };

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

iii create authOptions

there are different providers that can be used for authentication,
you can have a look at the next-auth docs to view how to implement 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,
};
},
}),
],
};

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'

shifting to handling sessions on the client side

v. creating a session provider

touch 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;

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>
);
}

and that's it, you can use the use session 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

--

--

No responses yet