Next.js Discord

Discord Forum

NextAuth example for NextJS 14

Unanswered
127.0.0.1 posted this in #help-forum
Open in Discord
Hi everyone. I'm very new to NextJS and just upgraded my project to NextJS 14 with the app dir.

I have my Prisma connection set up with an api route handler (/src/app/api/login/route.ts) that has some login content with prisma.

It works perfect the only thing i want is to have the sessions working. So that i can use a simple api to make it log the user in so that they can access the rest of the app + log them out with an api.

How can i do that?

8 Replies

Asian black bear
import { cookies } from "next/headers";

import getUserFromToken from "./helpers.auth";

const getCurrentUser = () => {
const token = cookies().get('jwt');

if(!token) {
return {
message: "No token found"
}
}

const user = getUserFromToken(token.value as unknown as string);

if(!user) {
return {
message: "No user found"
}
}

return user;
};

export default getCurrentUser;

import jwt, { JwtPayload } from 'jsonwebtoken';

import { User } from '@prisma/client';

const getUserFromToken = (token: string): JwtPayload | User | null => {
try {
const decodedToken = jwt.decode(token) as JwtPayload as User;

const { password, ...user } = decodedToken;

return user;
} catch (error) {
return {
error: "Error decoding token"
};
}
}

export default getUserFromToken;

You can do something like this which gets the user that you have created from the cookies.
Should this be the api route?
I havent created a cookie or anything im just checking in the datbase if the user exists nothing else @Asian black bear
Asian black bear
In your original question you said you wanted to log out a user? If this is the case i would go the way suggested and I can show you a log out route to delete the cookie.

However if you are checking for exisiting users to handle sign up and make sure you are not creating users with same email address you can create a prisma function like this.
export const createAccount = async (req: any): Promise<SignUpRequestDTO | RequestErrorDTO> => {
const { email, password, username } = req;

const userExists = await checkIfUserExists(email);

if (userExists) {
return {
error: 'User already exists'
};
}

const hashedPassword = await hashPassword(password);

const user = await createUser({
email,
password: hashedPassword,
username,
});

if (!user) {
return {
error: 'User could not be created'
}
}
return { user }
}

export const handleSignUp = async (req: NextRequest) => {
const request = await req.json();

const validationErrors = validateRequestBody(request, AuthValidationRules);

if (Object.keys(validationErrors).length > 0) {
return NextResponse.json({ errors: validationErrors }, { status: 422 });
}

const handler = await createAccount(request);

if ('error' in handler) {
return NextResponse.json({ error: handler.error }, { status: 422 })
}

const response = NextResponse.json({
message: 'User created Succesfully',
data: {
user: handler.user,
},
status: 200,
});

response.cookies.set('jwt', handler.token, { maxAge: 30 * 24 * 60 * 60 });

return response
}

const selectItems = {
id: true,
email: true,
username: true,
password: true,
isVerified: true,
role: true,
profileImageUrl: true,
};

export const checkIfUserExists = async (email: string, select?: Partial<SelectItems>) => {
const userExists = await prisma.user.findUnique({
where: {
email,
},
select: select || selectItems
});

return userExists;
}

export const createUser = async (data: any) => {
const user = await prisma.user.create({
data,
});
return user
}
If i have misunderstood please let me know
@Asian black bear No like i have a complete frontend page for logging in. When clicking the login button it goes to my login api route handler in the app dir. There i have a complete fucntioning script that takes the user input and checks if the user exists and if yes it redirects them to the dashboard. But before redirecting i want it to make some kind of session so that i can check on the dashboard if the user is logged in. What is the easiest way to do that?
@127.0.0.1 <@715182559683674213> No like i have a complete frontend page for logging in. When clicking the login button it goes to my login api route handler in the app dir. There i have a complete fucntioning script that takes the user input and checks if the user exists and if yes it redirects them to the dashboard. But before redirecting i want it to make some kind of session so that i can check on the dashboard if the user is logged in. What is the easiest way to do that?
Asian black bear
One method is to create and implement a cookie like the first code that I showed you above this will create a cookie and you jsut check for the current user which you get from the headers as soon as they hit login, if they have a valid session then you can show them what ever parts of the app you want but if not then you can just redirect to the login page for example, or you can use a third party library to create the session and check for the authentication such as https://auth0.com/docs/quickstart/webapp/nextjs/interactive or NextAuth