Home > Mobile >  How to prevent user for access inner page if not loggged in Using Reactjs
How to prevent user for access inner page if not loggged in Using Reactjs

Time:12-12

I am working with Reactjs and using nextjs framework,I am working on Login and logout module,I want if any user trying to access inner page without "loggged in" then he should redirect to "index/login" page,How can i do this ? Here is my current code if someone login with correct credentials

 const handleSubmit = (e: any) => {
          sessionStorage.setItem("email", response.data.email);
          const email = sessionStorage.getItem("email");
          router.push('/dashboard');
       }

CodePudding user response:

Well you can do this by holding a context in your whole project or a state or props in specific pages that need permission to view.

So let's assume you have a Dashboard page. You can handle your login in getServerSideProps for better experience and also redirect your user with redirect property before even letting the user to see your page:

export const DashboardPage = (props) => {
  return /* ... */;
};

export async function getServerSideProps(context) {
  const res = await fetch(`Your Login URL`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    }
  }

  return {
    props: data
  }
}

In this way you should use the logic in every page you have.

Instead you can send the login request from client and set the response to a context value and use that context in every other pages and components. Context File:

import React, { useState, useEffect } from 'react';

export const UserContext = React.createContext();

export function UserProvider({ children }) {
    const [userData, setUserData] = useState(null);
    const [isLoggedIn, setIsLoggedIn] = useState();
    
    const value = { userData, setUserData, isLoggedIn, setMode };

    const handleLogin = async () => {
        const res = await fetch(`Your Login URL`);
        if(res.status === 200) {
            const data = await res.json();
            setUserData(data);
            setIsLoggedIn(true);
        } else {
            setIsLoggedIn(false);
        }
    }

    useEffect(() => {
        handleLogin();
    }, []);

    return (
        <UserContext.Provider value={value}>
            { children }
        </UserContext.Provider>
    );
}

And then use the values in your pages, for example Dashboard:

export const DashboardPage = (props) => {
  const { isLoggedIn } = useContext(UserContext);

  useEffect(() => {
    if(isLoggedIn === false) {
      router.push('/login');
    }
  }, [isLoggedIn]);
  return /* ... */;
};

CodePudding user response:

I think for checking user authentication it's better to store email or token in cookie and in getServerSideProps check cookie (because you have no access to localStorage in it)

and in getServerSideProps you can access cookie via req.cookies or use cookies package

sth like this :

import Cookies from 'cookies';


export const getServerSideProps = async ({ req, res, locale, ...ctx }) => {
  if (req) {
   // const posts = axios.get...
    const cookies = new Cookies(req, res);
    const token = cookies.get('email');
    if (!token) {
      return {
        redirect: {
          destination: '/login',
          statusCode: 401
        }
      }
    }
    return {
      props: {
        posts,
        // your other props
       },
    };
  }
}

and in client code to set cookie you can use js-cookie package

forexample :

import Cookies from 'js-cookie'

 const handleSubmit = (e: any) => {
      const email = response.data.email
      Cookies.set('email', email )
      router.push('/dashboard');
   }
  • Related