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

Phoenix Bolerplate

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.

Subscribe for $39/mo to geat ahead!

Learn More

Related Quick Tips

Published 23 May - 2020

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