npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-axios-jwt

v1.8.0

Published

Axios interceptor to store, transmit, clear and automatically refresh tokens for authentication in a React Native environment

Downloads

875

Readme

react-native-axios-jwt

Store, clear, transmit and automatically refresh JWT authentication tokens in a React Native environment.

Looking for a web alternative? Check out axios-jwt

What does it do?

Applies a request interceptor to your axios instance.

The interceptor automatically adds an access token header (default: Authorization) to all requests. It stores accessToken and refreshToken in AsyncStorage and reads them when needed.

It parses the expiration time of your access token and checks to see if it is expired before every request. If it has expired, a request to refresh and store a new access token is automatically performed before the request proceeds.

Installation

1. Install async-storage

Install package

With npm:

npm install @react-native-async-storage/async-storage

With Yarn:

yarn add @react-native-async-storage/async-storage

With Expo CLI:

expo install @react-native-async-storage/async-storage

Link Android & iOS packages

  • React Native 0.60+
npx pod-install
  • React Native <= 0.59
react-native link @react-native-async-storage/async-storage

Please follow the async-storage installation instructions if you encounter any problems while installing async-storage

2. Install this library

With npm:

npm install react-native-axios-jwt

With Yarn:

yarn add react-native-axios-jwt

How do I use it?

  1. Create an axios instance
  2. Define a token refresh function
  3. Configure the interceptor
  4. Store tokens on login with setAuthTokens()
  5. Clear tokens on logout with clearAuthTokens()

Applying the interceptor

// api.ts

import { IAuthTokens, TokenRefreshRequest, applyAuthTokenInterceptor } from 'react-native-axios-jwt'
import axios from 'axios'

const BASE_URL = 'https://api.example.com'

// 1. Create an axios instance that you wish to apply the interceptor to
export const axiosInstance = axios.create({ baseURL: BASE_URL })

// 2. Define token refresh function.
const requestRefresh: TokenRefreshRequest = async (refreshToken: string): Promise<string> => {

  // Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor
  // because this will result in an infinite loop when trying to refresh the token.
  // Use the global axios client or a different instance
  const response = await axios.post(`${BASE_URL}/auth/refresh_token`, { token: refreshToken })

  return response.data.access_token
}

// 3. Add interceptor to your axios instance
applyAuthTokenInterceptor(axiosInstance, { requestRefresh })

Login/logout

// login.ts

import { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'react-native-axios-jwt'
import { axiosInstance } from './api'

// 4. Log in by POST-ing the email and password and get tokens in return
// and call setAuthTokens with the result.
const login = async (params: ILoginRequest) => {
  const response = await axiosInstance.post('/auth/login', params)

  // save tokens to storage
  await setAuthTokens({
    accessToken: response.data.access_token,
    refreshToken: response.data.refresh_token
  })
}

// 5. Log out by clearing the auth tokens from AsyncStorage
const logout = () => clearAuthTokens()

// Check if refresh token exists
if (isLoggedIn()) {
  // assume we are logged in because we have a refresh token
}

// Get access to tokens
const accessToken = getAccessToken().then(accessToken => console.log(accessToken))
const refreshToken = getRefreshToken().then(refreshToken => console.log(refreshToken))

Configuration

applyAuthTokenInterceptor(axiosInstance, {
  requestRefresh,  // async function that takes a refreshToken and returns a promise the resolves in a fresh accessToken
  header = "Authorization",  // header name
  headerPrefix = "Bearer ",  // header value prefix
})

Caveats

  • Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.

Non-TypeScript implementation

//api.js

import { applyAuthTokenInterceptor } from 'react-native-axios-jwt';
import axios from 'axios';

const BASE_URL = 'https://api.example.com'

// 1. Create an axios instance that you wish to apply the interceptor to
export const axiosInstance = axios.create({ baseURL: BASE_URL })

// 2. Define token refresh function.
const requestRefresh = async (refresh) => {
    // Notice that this is the global axios instance, not the axiosInstance!
    const response = await axios.post(`${BASE_URL}/auth/refresh_token`, { refresh })

    return response.data.access_token
};

// 3. Apply interceptor
// Notice that this uses the axiosInstance instance.
applyAuthTokenInterceptor(axiosInstance, { requestRefresh }); 

Login/logout

//login.js

import {
  isLoggedIn,
  setAuthTokens,
  clearAuthTokens,
  getAccessToken,
  getRefreshToken,
} from 'react-native-axios-jwt';
import { axiosInstance } from '../api';

// 4. Log in by POST-ing the email and password and get tokens in return
// and call setAuthTokens with the result.
const login = async (params) => {
  const response = await axiosInstance.post('/auth/login', params)

  // save tokens to storage
    await setAuthTokens({
    accessToken: response.data.access_token,
    refreshToken: response.data.refresh_token
  })
}

// 5. Log out by clearing the auth tokens from AsyncStorage
const logout = () => clearAuthTokens()

// Check if refresh token exists
if (isLoggedIn()) {
  // assume we are logged in because we have a refresh token
}

// Get access to tokens
const accessToken = getAccessToken().then(accessToken => console.log(accessToken))
const refreshToken = getRefreshToken().then(refreshToken => console.log(refreshToken))


// Now just make all requests using your axiosInstance instance
axiosInstance.get('/api/endpoint/that/requires/login').then(response => { })