Django Integration
Cookie Auth + CSRF
Django add protection against Cross Site Request Forgery, by requiring the 'X-CSRFToken' header in requests.
Additionally Django's authentication uses cookies, so we need to send credentials fetch credentials. If you use an auth type other than the default 'django.contrib.auth', see authentication guide for more examples.
getCookie
DjangoEndpoint
MyResource
import { RestEndpoint, type RestGenerics } from '@data-client/rest'; import getCookie from './getCookie'; export default class DjangoEndpoint< O extends RestGenerics = any, > extends RestEndpoint<O> { async getRequestInit(body: any): Promise<RequestInit> { return { ...(await super.getRequestInit(body)), credentials: 'same-origin', }; } getHeaders(headers: HeadersInit) { if (this.method === 'GET') return headers; return { ...headers, 'X-CSRFToken': getCookie('csrftoken'), }; } }
Usage
import { MyResource } from './MyResource'; MyResource.partialUpdate({ id: 1 }, { title: 'Signing in with cookies' });
PATCH/my/1
- x-csrftoken
- xyz
{
"title": "Signing in with cookies"
}200 OK
{
"id": "1",
"title": "Signing in with cookies"
}