CSRF next js

I tried to use next js with Django backed with session authentication. My Django API work fine. CSRF was set in Browser Cookie ,but when submit the post request via Nextjs Server Action return an error csrf Token not Set. Can anyone tell how to fix Csrf not set. Or pls share your code ,django session authentication with next js ?

Welcome @Ekaluk52003 !

First, a side note: When you’re requesting assistance with an error, please post the complete error and stacktrace from the server console. If there is no error on the console, then post the error from the browser window. In this particular case, there are like four different messages that the CSRF middleware will return, and the precise wording in important.

From your description though, I’m going to guess that while the cookie may be set, you did not include the CSRF Token in your response. See the docs at How to use Django’s CSRF protection | Django documentation | Django for your options.

To fix this issue, ensure you’re sending the CSRF token with your POST request. Django sets the csrftoken in cookies, so extract it from the cookie in your Next.js app and include it in the X-CSRFToken header.
You Can use axios interceptors if you’re using axios like the example below to extract the token from the cookies and insert it in the request.

import axios from ‘axios’;
import cookie from ‘js-cookie’;

axios.interceptors.request.use((config) => {
const csrftoken = cookie.get(‘csrftoken’);
if (csrftoken) {
config.headers[‘X-CSRFToken’] = csrftoken;
}
return config;
});