Psst. It would be super cool if you could try the new Phoenix Boilerplate!

Try now

Quick Tip

Use javascript fetch to post to a Phoenix controller


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'}})

What are you working on?

If you want, you can send me a link to your Phoenix or Phoenix LiveView project so. Lets connect on Twitter or Linkedin.

- Andreas Eriksson, web developer since 2005

Related Quick_tips

Published 23 May

Delete unused node_module folders


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..