Skip to content
July 07, 2019

Feathers authentication client

client/feathers.js

import createFeathersClient from '@feathersjs/feathers'
import auth from '@feathersjs/authentication-client'
import socketio from '@feathersjs/socketio-client'
import io from 'socket.io-client'

const socket = io()
const feathers = createFeathersClient()
feathers.configure(socketio(socket))
feathers.configure(
  auth({
    storage: window.localStorage,
    storageKey: 'access-token',
    path: '/authentication'
  })
)

To login using username/email and password:

client/feathers.js

export async function authenticateWithPassword() {
  const { user } = await feathers.authenticate({ strategy: 'local', email, password })
}

To authenticate a previously logged in user upon loading the app:

export async function authenticateWithToken() {
  const accessToken = await feathers.authentication.getAccessToken()

  if (!accessToken) {
    return { guest: true }
  }

  try {
    const { user } = await feathers.authenticate({ strategy: 'jwt', accessToken })
    return user
  } catch (err) {
    console.error('Failed to authenticate', err)
    if (err.code === 401 || err.code === 404) {
      feathers.authentication.removeAccessToken()
      return { guest: true }
    } else {
      throw err
    }
  }
}

Note: you could simply call feathers.authenticate() instead of manually managing the token the way I’ve done above. I prefer this way of doing it to avoid logging users out when there are temporary server or internet connectivity disruptions. That is, feathers.authenticate() will remove the token without checking the error code, whereas the code above checks if the error is one 401 or 404 before permanently removing the token from local storage.