Authentication Wrapper Around m.request

by cmnstmntmn

Level: beginner • Mithril.js Version: latest

This example is showing an authentication wrapper around Mithril.js' m.request. Normally, we would store and retrieve the bearer token in the browsers window.localStorage or window.sessionStorage. In this example this is only hinted while doing some kind of fake authentication, but you should get the point. So, let's see the example.

Live Example


Type Name URL


var api = {
  request: (options) => {
    options.config = xhr => {
      xhr.setRequestHeader('Authorization', 'Bearer ' + api.token())
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

    return m.request(options).catch((error) => {
      if(error.code == 401) m.route.set("/login")

      throw error

  token: (value) => {
    if (value)
      localStorage.setItem('token', value)

    return localStorage.getItem('token')
  tokenRemove: () => localStorage.removeItem('token')

// -- utils
function getRequestDemo() {
      method: "GET", url: ""
  }).then(function(response) {
    //-- handle response
    console.log('Success, Auth:', response.headers.Authorization)
    //-- handle error

function checkAuth() {
  if (!api.token())
    return false
    return true

function doFakeLogin(username) {
  // -- simulate login

// -- app code

var loginForm = {
  model: {
    username: '',
    password: ''
  view: function(vnode) {
      return !checkAuth() ? [
        m('input[type="text"][placeholder="Username"]', {
          onkeyup: function(e){
            vnode.state.model.username =
        m('input[type="password"][placeholder="Password"]', {
          onkeyup: function(e){
            vnode.state.model.password =
        m('button', {
        onclick: () => doFakeLogin(vnode.state.model.username)
      }, 'Login')
    : [
        m('h2', 'Hooray!'),
        m('button[type="button"]', {
          onclick: api.tokenRemove
        }, 'Logout/Destroy token'),
        m('button[type="button"]', {
          onclick: getRequestDemo
        }, 'Make a POST request'),
        m('span', 'and watch the request in the console')

var app = {
  view: function(vnode) {
    return [
      m('h1', 'Wrapper around m.request to handle authentication with localstorage'),
        m('li', 'login - markup only;'),
        m('li', 'a token is added to sessionStorage;'),
        checkAuth() && m('li', {style: "color:green"}, 'make a POST request - Authorization header is now present')

m.mount(document.body, app);

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

Here we can see use cases of different Mithril.js API methods like m.request, m.route or m.mount, besides the centrepiece m() hyperscript function. Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.

The example was written by cmnstmntmn, last edits were made on 26 October 2021.


Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub