Writing an authentication middleware with no library
Answered
Birman posted this in #help-forum
BirmanOP
Hi. So I decided to implement authentication in Next with no library to have more understanding of this topic. I managed to mock an authentication approach using request cookies. But I want to use request headers instead which I was unable to achieve so far. Can anyone help me solve this issue?
In
In
In
In
src/app/login/page.tsx"use client";
export default function Page() {
const router = useRouter();
async function handleFormSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const email = formData.get("email");
const password = formData.get("password");
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (data.success == true) router.push("/");
}
return <form onSubmit={handleFormSubmit}>...</form>
}In
src/app/api/auth/login/route.ts"use server";
import { cookies } from "next/headers";
export async function POST(req: Request) {
const { email, password } = await req.json();
// const headers = req.headers.get("Authorization")?.split(" ")[1];
if (email == "admin@email.com" && password == "password") {
cookies().set({ name: "accessToken", value: "Access-Token", httpOnly: true, path: "/" });
cookies().set({ name: "refreshToken", value: "Refresh-Token", httpOnly: true, path: "/" });
return Response.json({ success: true });
}
return Response.json({ success: false });
}In
src/middleware.tsimport { cookies } from "next/headers";
export async function middleware(request: NextRequest) {
const accessToken = cookies().get("accessToken");
if (!accessToken) return NextResponse.redirect(new URL("/login", request.url));
if (String(accessToken) === "Access-Token") return NextResponse.next();
}
export const config = { matcher: ["/", "/dashboard"] };Answered by Shy Albatross
OP I don't understand your follow up question TBH, middleware runs before any endpoint (and by "endpoint" I assume you mean a route handler) but like I said, cookies get autmatically attached to every request from he browser, whereas you need to add the custom header yourself
7 Replies
BirmanOP
Non working example replication but with Next
https://stackblitz.com/edit/stackblitz-starters-nlbxok
My actual local project uses Next
13.5.1 https://stackblitz.com/edit/stackblitz-starters-nlbxok
My actual local project uses Next
14.0.3Shy Albatross
with the way you're manually fetching the API route and not using server actions on the form directly,
src/app/api/auth/login/route.ts should not say "use server", consult the docs on server actions as to what that meansas for your headers question: unlike cookies, which get sent along with every request, the headers don't stick, so you'd need something to always set those headers
while cookies are meant for this, headers are not, since you'd be manually adding them to all requests
BirmanOP
I would like to know if it would be possible to implement an endpoint that will get passed through the middleware? Such that I might then be able to access the token from the
headers() in my middleware functionyou dont put use server in a route
Shy Albatross
OP I don't understand your follow up question TBH, middleware runs before any endpoint (and by "endpoint" I assume you mean a route handler) but like I said, cookies get autmatically attached to every request from he browser, whereas you need to add the custom header yourself
Answer