Someone tell me why this isnt a server action?
Answered
Vachan MN posted this in #help-forum
"use server";
import {
createSession,
generateSessionToken,
invalidateSession,
validateSessionToken,
} from "./auth_api";
import prismaClient from "./db";
import { sha256 } from "@oslojs/crypto/sha2";
import { cookies } from "next/headers";
export async function login(email: string, password: string) {
const passwordHash = sha256(new TextEncoder().encode(password)).toString();
const user = await prismaClient.user.findUnique({
where: {
email,
passwordHash,
},
select: {
id: true,
name: true,
email: true,
},
});
if (user === null) {
return null;
}
const token = generateSessionToken();
const session = await createSession(token, user.id);
(await cookies()).set({
name: "session",
value: token,
httpOnly: true,
});
return session;
}
export async function logout() {
const biscuits = await cookies();
const token = biscuits.get("session");
if (!token) {
return;
}
await invalidateSession(token?.value as string);
biscuits.delete("session");
}
export async function getSession() {
const biscuits = await cookies();
const token = biscuits.get("session");
console.log(token);
if (!token) {
return null;
}
const session = await validateSessionToken(token.value);
if (session.session === null) {
biscuits.delete("session");
}
return session;
} ⨯ Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-optionsWhy is
getSession() not a server action? I just want to understand what qualifies as a server action and what doesnt...Answered by Asian black bear
You are very likely calling
getSession as a "server-side function" from a server component. Server components cannot modify cookies because headers have already been sent by the time. Server actions are glorified POST endpoints and not just "server-side functions" you call from your components, therefore your directive doesn't do anything if you do consume the function the way I assume.7 Replies
Asian black bear
You are very likely calling
getSession as a "server-side function" from a server component. Server components cannot modify cookies because headers have already been sent by the time. Server actions are glorified POST endpoints and not just "server-side functions" you call from your components, therefore your directive doesn't do anything if you do consume the function the way I assume.Answer
ahhh
damn man, auth is becoming painful in nextjs
middleware wont work with db
I thought this might work
nvm then
thanks for the help!