Quick Tip

Use javascript fetch to post to a Phoenix controller

javascriptcsrf

As in the case with Rails, Phoenix also has protection against cross site request forgery (crfs). If you want to post to a controller from a javascript file you need to add the token as a header manually. However, in phoenix the csrf token is provided when you render a form. So, unless there is already a form on the page, there is no token to read. To get around this, add this in the page header:

<%= csrf_meta_tag() %>

And then the post can be triggered with:

const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

fetch('/posts', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': token
  },
  body: JSON.stringify({post: {title: 'Awesome blogpost title'}})
})

Phoenix Boilerplate

Generate a Phoenix Boilerplate and save hours on your next project.

Try now

SAAS Starter Kit

Get started and save time and resources by using the SAAS Starter Kit built with Phoenix and LiveView.

Learn More

Related Quick_tips

Published 23 May - 2020

Delete unused node_module folders

javascript

Tired of all node_modules folders taking up gigabytes of hard drive space? Did you know theres is a command to find and delete them? If you are lik..