Is there a way to use Next.js API Routes to Authenticate Django Rest Framework backend?

Viewed 504

I'm using DRF as a backend to Next.js frontend. I followed this very fine tutorial to set up authentication, but I read I should use Next.js API Routes as proxy to the DRF API Routes and I can do that on any route other than the authentication one because I must send the X-CSRFToken and credentials: "include" in the request headers. Currently I'm getting the CSRF Token on page load with useEffect:

useEffect(()=> {

    fetch("http://localhost:8000/api-auth/csrf",{
      credentials: "include"
    })
    .then( res => setCsrf(res.headers.get("X-CSRFToken")))
    .catch( err => console.error(err))

  },[])

Im using a direct route to DRF API "http://localhost:8000/api-auth/csrf" instead of a Next.js API like "/api-auth/csrf". The same happens with the handleLogin function:

const handleLogin = async (event) => {
    event.preventDefault();

    fetch("http://localhost:8000/api-auth/login/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": csrf
      },
      credentials: "include",
      body: JSON.stringify(formValues),
    })
    .then(() => Router.push("/profile"))
  };

It is working like this, but I can't set credentials using Next.js API Routes. Even using the same pattern it doesn't work. I think I'm missing some fundamental concept here and I looked it up but couldn't find. If anyone can help I'd appreciate :)

0 Answers
Related