I am implementing basic authentication in a Next.js app, but redirect to homepage doesn`t work in auth.ts file.
I put part of my code that implement loginForm blow :
//loginForm.tsx
import { authenticate } from '../actions/auth';
export default function LogIn() {
return (
<form action={authenticate}>
.
.
.
<button className="mt-4 w-full" >
Log in
</button>
</form>
);
}
//auth.ts
"use server";
import { redirect } from "next/navigation";
import createSession from "../lib/session";
import { signIn } from "../server";
export async function authenticate(formData: FormData) {
const result = await signIn(formData);
if (result) {
createSession(result);
redirect("/");
}
}
//session.ts
import "server-only"
import { cookies } from "next/headers";
export default function createSession(userId: number) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const session = `sessionIs${userId}`;
cookies().set("session", session, {
httpOnly: true,
secure: true,
expires: expiresAt,
path: "/",
});
}
I tried the code above but it didnt work, also I tried NextResponse.redirect but it didn
t work too.
New contributor
Behnaz Kiani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.