Jaya Guru
Jaya Guru

Reputation: 11

How to solve this problem of getting two csrf token values?

I have been using next.js to build a custom csrf middleware. The problem is that it has two csrf token values, one in the login form and one in the cookie. Even though I have taken the csrf token value from cookies() function, But it generated two csrf token values.

This is the middleware function.

import { NextResponse } from "next/server";

export default function middleware(req, res) {
    if (req.nextUrl.pathname === "/") {
        const res = NextResponse.next();
        const token = String(Math.round(Math.random()*10000000))
        res.cookies.set("CSRFToken", token, {path:"/", httpOnly:true});
        return res;
    }
    return NextResponse.next();
}

This is the code in the pages.js,

import { cookies } from "next/headers";
import LoginPage from "./login";

export default async function Home() {
  let csrfToken = cookies().get("CSRFToken").value
  console.log(csrfToken);
  return <LoginPage csrfmdltoken={csrfToken} />;
}

CSRF token in the form. CSRF Token in the cookies.

Upvotes: 0

Views: 28

Answers (0)

Related Questions