PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Written By
Views

A simple High-Order Component in React for authentication in Typescript

This is for authentication, when users access certain pages by typing in the URL on browser, they will get redirected to the login page because they haven't login yet.

Let's assume after login successfully, you save the token in local storage

localStorage.setItem('access.token', token);

Now, let's write the HOC called withAuthentication

import React, { ComponentType, FC } from 'react';
import { Redirect } from 'react-router-dom';

const withAuthentication = <P extends any>(
  Component: ComponentType<P>,
): FC<P> => (props) => {
    const isAuthenticated = localStorage.getItem('access.token) as string;
    if (isAuthenticated) {
      return <Component {...props} />;
    }
    return (
      <Redirect
        to={{
          pathname: '/login',
        }}
      />
    );
  };

export default withAuthentication;

What I do in this HOC is very simple. First, I get the token from the localStorage. Then add some conditional to render a component or the Redirect component from the react-router-dom to redirect the user back to the login page.

The HOC in action

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from 'react-router-dom';

import withAuthentication from 'hocs/withAuthentication';

function App() {
  return (
     <Router>
       <StyledDivApp>
         <Switch>
           <Route
             exact
             path="/dashboard"
             component={withAuthentication(Dashboard)}
            />
          </Switch>
       </StyledDivApp>
     </Router>
  );
}

export default App;

Comments (0)

loading comments