1.0.71 • Published 3 years ago

rex-jwt-client v1.0.71

Weekly downloads
406
License
ISC
Repository
github
Last release
3 years ago

rex-jwt-client

rex-jwt-client is the client side corresponding package for rex-jwt-middleware. Easily manage client side authentication on a react/express application.

Contents

Installation

npm i rex-jwt-client

or

yarn add rex-jwt-client

Example

First, let's take a look at a working example. We'll break it down afterwards in the coming sections.

import React from  'react'
import { BrowserRouter as Router, Switch, Route, Link } from  'react-router-dom'
import { 
  AuthProvider, 
  PrivateRoute, 
  PublicRoute,
  PublicLink,
  PrivateLink
} from  'rex-jwt-client'
import Home from  './pages/Home'
import Login from  './pages/Login'
import Register from  './pages/Register'
import SecretPage from  './pages/SecretPage'
import Loader from  './components/Loader'

const  App  = () => {
  return (
    <AuthProvider  refreshRoute='/api/refresh'  loader={Loader}>
      <Router>
        <nav>
          <Link  to='/'>Home</Link>
          <PrivateLink  to='/secret'>Secret</PrivateLink>
          <PublicLink  to='/login'>Log In</PublicLink>
          <PublicLink  to='/register'>Register</PublicLink>
        </nav>
        <Switch>
          <Route  
            exact
            path='/' 
            component={Home}
          />
          <PrivateRoute
            exact  
            path='/secret'  
            redirect='/'  
            component={SecretPage} 
          />
          <PublicRoute
            exact
            path='/login'
            redirect='/secret'
            component={Login}
          />
          <PublicRoute
            exact
            path='/register'
            redirect='/secret'
            component={Register}
          />
        </Switch>
      </Router>
    </AuthProvider>
  )
}
export  default App

Let's break it down piece by piece.

AuthProvider

The AuthProvider is just a React context provider that holds all of the user's authentication details. It takes a couple props: | prop | description | |--|--| | refreshRoute | Requried parameter, which is a route that should match the route set up to refresh the accessToken in the back end. |

| loader | Optional parameter. If you want one specific loading component to be accessible in every place where a request with useProtectedFetch is made, just add your component here. |

To access the loader in other child components of the AuthProvider:

import  { AuthProvider }  from  'rex-jwt-client'
const { loader } = useContext(AuthProvider.contextType)

Routing Components

All Route and Link components are dependent on the package react-router-dom and must be used in a BrowserRouter component as shown above. A CLI will be made in the future to more easily incorporate this option. For now, react-router-dom can be installed by doing:

npm i react-router-dom

or

yarn add react-router-dom

PrivateLink and PublicLink

A PrivateLink is a link that only exists/gets shown when a user's access token is. A PublicLink is a link that's only shown when a user is not logged in. | prop | description | |--|--| | to | Path that the link links to. Same as an href in an anchor tag. |

PrivateRoute and PublicRoute

A PrivateRoute is a route that's accessible only when a user is logged in. A PublicRoute is a route that's accessible only shown when a user is not logged in. Any of the same props that can be added to a Route component from react-router-dom can be added to these components with one addition. The following are the main props: | prop | description | |--|--| | component | Component to be shown when URL matches path. | | path | URL that corresponds to component. | | redirect | Redirect URL. If authenticated user tries accessing PublicRoute, they will be redirected to this URL. The same with an unauthenticated user trying to access a PrivateRoute. | | exact | Makes sure that component is shown only if URL matches path exactly. |

useProtectedFetch

This is a special hook that fetches and/or sends info along a protected route in the api. If the access token has expired, but the refresh token hasn't expired, it will refresh the access token before accessing the protected route.

Let's take a look at the SecretPage component we imported in the example above:

import React, { useContext } from  'react'
import { AuthProvider, useProtectedFetch } from  'rex-jwt-client'

const  SecretPage  = () => {
  const { loader: Loader } = useContext(AuthProvider.contextType)
  const { data, loading, error } = useProtectedFetch({
    route: '/api/secret',
    method: 'GET',
    responseType: 'text',
  })

  if (loading) return  <Loader  />

  if (error) return  <div>{error}</div>

  return  <div>Secret data: {data}</div>
}
export  default SecretPage

useProtectedFetch takes the following parameters: | parameter | description | Is required | |--|--|--| | route | Route that the request is being made to. | ✔ | | method | Method being used for request. 'GET', 'POST', etc. | ✔ | | headers | Additional parameters like 'Content-Type', same as headers that can be put in a regular fetch call. | ✖ | | body | Body of request. | ✖ |

| responseType | Specify how the data will be parsed upon being received. Currently, "text" and "json" are the only valid options. If no option is specified, json is used. | ✖ |

As shown above, this hook returns 3 things:

  • data - Parsed data received from fetch request.
  • loading - State that shows whether or not we're still waiting for data.
  • error - Error message if fetch call went wrong.

Description of the process:

This package uses two JWT's to carry out authentication, an access token and a refresh token. When a user logs into the site, they receive these two tokens. The access token can be stored either in memory or localStorage, and the refresh token gets stored in an HTTP only cookie.

The access token is what allows a user to access protected routes. Once the access token expires, as long as the refresh token hasn't expired, the refresh route can be used to get a new access token before accessing a protected route.

I hope this package can help make react/express authentication easier, and if there's any improvements that can be made, I'm always open to looking at pull requests in the GitHub repo.

All the best. 👋

1.0.71

3 years ago

1.0.70

3 years ago

1.0.62

3 years ago

1.0.61

3 years ago

1.0.60

3 years ago

1.0.66

3 years ago

1.0.65

3 years ago

1.0.64

3 years ago

1.0.63

3 years ago

1.0.69

3 years ago

1.0.68

3 years ago

1.0.67

3 years ago

1.0.49

3 years ago

1.0.51

3 years ago

1.0.50

3 years ago

1.0.55

3 years ago

1.0.54

3 years ago

1.0.53

3 years ago

1.0.52

3 years ago

1.0.59

3 years ago

1.0.58

3 years ago

1.0.57

3 years ago

1.0.56

3 years ago

1.0.44

3 years ago

1.0.43

3 years ago

1.0.42

3 years ago

1.0.48

3 years ago

1.0.47

3 years ago

1.0.46

3 years ago

1.0.45

3 years ago

1.0.41

3 years ago

1.0.40

3 years ago

1.0.39

3 years ago

1.0.38

3 years ago

1.0.37

3 years ago

1.0.36

3 years ago

1.0.34

3 years ago

1.0.33

3 years ago

1.0.32

3 years ago

1.0.30

3 years ago

1.0.29

3 years ago

1.0.28

3 years ago

1.0.27

3 years ago

1.0.26

3 years ago

1.0.25

3 years ago

1.0.24

3 years ago

1.0.23

3 years ago

1.0.22

3 years ago

1.0.21

3 years ago

1.0.19

3 years ago

1.0.20

3 years ago

1.0.18

3 years ago

1.0.17

3 years ago

1.0.16

3 years ago

1.0.9

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.15

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.2

3 years ago

1.0.3

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago