0

My backend has an endpoint: /auth/jwt/create that returns a JSON response containing the access and refresh tokens. With my current backend setup, I send the tokens in both the response body and in HTTP only cookie. But I am confused how to store this with Nextjs server actions and send it with every request. Can someone tell me the complete workflow?

EDIT

With the following frontend setup, the backend COOKIE is still empty. I don't fully understand Next.js cookies() but using it feels like duplicating the logic again. My backend is already setting the cookies with access and refresh tokens.

// login.tsx:
export async function login(formData: FormData) {
  "use server";
  const username = formData.get("username");
  const password = formData.get("password");

  const data = await fetch("http://localhost:8000/api/auth/jwt/create/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ username, password }),
  });
  const result = await data.json(); // result = { access: "...", refresh: "..." } (or {} if tokens are only set in cookie)
  console.log("Login successful");
}

export default function LoginPage() {
  return (
    <div>
      <form action={login}>...</form>
    </div>
  );
}

User.tsx:

export default async function Page() {
  const data = await fetch("http://localhost:8000/api/auth/users/me/", {
    method: "GET",
    credentials: "include",
  });
  const user = await data.json();
  console.log(user); // {detail: 'Authentication credentials were not provided.'}

  return (...);
}

Backend response (cookies are set by backend)

Backend response in POSTMAN (cookies set by backend)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.