Skip to main content

Django Integration

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.

export default function getCookie(name): string {
  let cookieValue = '';
  if (document.cookie && document.cookie != '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) == (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
import { RestEndpoint } 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'),
    };
  }
}
import { createResource, Entity } from '@data-client/rest';
import DjangoEndpoint from './DjangoEndpoint';

class MyEntity extends Entity {
  id = '';
  title = '';
  pk() {
    return this.id;
  }
}

export const MyResource = createResource({
  path: '/my/:id',
  schema: MyEntity,
  Endpoint: DjangoEndpoint,
});
Request
import { MyResource } from './MyResource';
MyResource.get({ id: 1 });
Request
GET /my/1
Content-Type: application/json
X-CSRFToken: xyz
Cookie: session=abc;
Response200
{
"id": "1",
"title": "this post"
}