Why am I getting the error (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.)?

I'm trying to send from React a PUT request to my Django server for updating a Django model field. Here's the code

const handleStatusChange = async (projectId, newStatus) => {
        try {
            const response = await fetch(`/api/project/${projectId}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({ status: newStatus })
            });

            if (response.ok) {
                setProjects(prevProjects => 
                    prevProjects.map(project => 
                        project.id === projectId ? { ...project, status: newStatus } : project
                    )
                );
                setStatusDropdown(null); 
                setUpdatingProjectId(null); 
            } else {
                console.error('Failed to update project status');
            }
        } catch (error) {
            console.error('Error updating project status:', error);
        }
    };

The problem is that the console logs the message 'Failed to update project status' because of the server error: Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status WARNING:django.security.csrf:Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status [06/Dec/2024 17:37:21] "PUT /api/project/1/status HTTP/1.1" 403 2549. I have no clue of what's leading to the error. I applied the same logic to another PUT request in other page and I didn't have the issue. Can somebody explain please how I can manage the csrf token length? I'm not "manually" generating such token.

I'll share the complete console error if helps:

index.js:25 Failed to update project status
handleStatusChange  @   index.js:25
await in handleStatusChange     
onClick @   index.js:61
callCallback    @   react-dom.development.js:3942
invokeGuardedCallbackDev    @   react-dom.development.js:3991
invokeGuardedCallback   @   react-dom.development.js:4053
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:4067
executeDispatch @   react-dom.development.js:8273
processDispatchQueueItemsInOrder    @   react-dom.development.js:8305
processDispatchQueue    @   react-dom.development.js:8318
dispatchEventsForPlugins    @   react-dom.development.js:8329
(anónimo)   @   react-dom.development.js:8538
batchedEventUpdates$1   @   react-dom.development.js:22426
batchedEventUpdates @   react-dom.development.js:3742
dispatchEventForPluginEventSystem   @   react-dom.development.js:8537
attemptToDispatchEvent  @   react-dom.development.js:6035
dispatchEvent   @   react-dom.development.js:5954
unstable_runWithPriority    @   react.development.js:2764
runWithPriority$1   @   react-dom.development.js:11306
discreteUpdates$1   @   react-dom.development.js:22443
discreteUpdates @   react-dom.development.js:3753
dispatchDiscreteEvent   @   react-dom.development.js:5919

Back to Top