Get started with JN Snippets

JN Snippets is a powerful, feature-packed frontend toolkit. Build anything—from prototype to production—in minutes.

  • Login using Wordpress API's | Local Storage & Cookie

    Enable WordPress REST API
    WordPress already includes a REST API, so ensure it's enabled by default.
    For user authentication, you'll need the JWT Authentication plugin.
    JWT Plugin
    Add the following lines to your wp-config.php file:

    define('JWT_AUTH_SECRET_KEY', 'jagga-is-back');
    define('JWT_AUTH_CORS_ENABLE', true);
    
                                    

    Ensure your WordPress .htaccess file supports the API by adding:

    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
    
                                    
  • Login Form Example using Local Storage

    You'll use axios to communicate with the WordPress REST API.

    import React, { useState } from 'react';
    import axios from 'axios';
    import { useNavigate } from 'react-router-dom'; 
    // use navigate is used for redirect the user after successful login
    
    
    function LoginForm() {
        const [getInputValues, holdInputValues] = useState({
            fName : '',
            eMail : '',
            pHone : '',
            pWord : ''
        });
        const [responseMessage, setResponseMessage] = useState('');
        const navigate = useNavigate(); // Initialize useNavigate for redirects
        const GetInputEvent = (event) => {
            const {name, value} = event.target;
            holdInputValues((prevVal) => {
                //console.log(prevVal);
                return{
                    ...prevVal,
                    [name]: value,
                }
            })
        }
        const onSubmitForm = async (event) => {
            event.preventDefault();
            console.log(getInputValues.eMail);
            console.log(getInputValues.pWord);
    
    
            try {
                const response = await axios.post(`$site-url]/wp-json/jwt-auth/v1/token`, {
                    username: getInputValues.eMail,
                    password: getInputValues.pWord,
                });
                localStorage.setItem('token', response.data.token); // Save the JWT token
                setResponseMessage('Login Successfull');
                // Redirect to dashboard after login
                navigate('/dashboard'); // redirects user
            } catch (error) {
                // console.error('Login failed', error.response.data);
                setResponseMessage('Invalid username or password.');
            } 
        }
        return (
        <>
            <section className="formContact">
                <div className="container">
                    <div className="row">
                    <div className="col-md-7">
                        <form className="formWrapper" onSubmit={onSubmitForm}>
                            <div className="ap_form">
                                <h1>Hello</h1>
                                <input type="email" placeholder="Email" value={getInputValues.eMail} name="eMail" onChange={GetInputEvent}/>
                                <input type="password" placeholder="Password" value={getInputValues.pWord} name="pWord" onChange={GetInputEvent}/>
                                <button>Submit</button>
                                {responseMessage && <p>{responseMessage}</p>}
                            </div>
                        </form>
                    </div>
                    </div>
                </div>
            </section>
        </>
        );
    }
    export default LoginForm;
    
                                    
  • Use following for protected Components

    Add the Code Open ProtectedRoute.js and paste the code:

    import React from 'react';
    import { Navigate } from 'react-router-dom';
    
    const ProtectedRoute = ({ children }) => {
        const token = localStorage.getItem('token');
        return token ? children : ;
    };
    
    export default ProtectedRoute;
    
                                    

    Import those component in App.js which are opens only after login

    import ProtectedRoute from './inc/global/ProtectedRoute';
    import Dashboard from './inc/pages/Dasboard';
    
                                    

    Then add all those components in routes like following in App.js

    <Route
    path="/dashboard"
    element={
        <ProtectedRoute>
        <Dashboard />
        </ProtectedRoute>
    }
    />
    
                                    
  • Check if user is already login

    Check if user is already login and open login page then automatically redirect to dashboard page
    Import “useEffect” in login component

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

    Add the following component in inside login component.
    Redirect if already logged in

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
        navigate('/dashboard'); // Redirect to dashboard if token exists
        }
    }, [navigate]);
    
                                    
  • Login Functionality using Cookie

    Then import js-cookie in login component. npm install js-cookie

    import Cookies from 'js-cookie';
    
                                    

    Cookie Code

    const onSubmitForm = async (event) => {
        event.preventDefault();
    
        try {
            const response = await axios.post(`$[site-url]/wp-json/jwt-auth/v1/token`, {
                username: getInputValues.eMail,
                password: getInputValues.pWord,
            });
            Cookies.set('authToken', response.data.token, { expires: 4, secure: true });
            setResponseMessage('Login Successfull');
            navigate('/dashboard');
        } catch (error) {
            // console.error('Login failed', error.response.data);
            setResponseMessage('Invalid username or password.');
        }   
    }
    
    
                                    
  • Use following for protected Components using js-cookie

    Add the Code Open ProtectedRoute.js and paste the code:

    import React from 'react';
    import { Navigate } from 'react-router-dom';
    const ProtectedRoute = ({ children }) => {
        const token = Cookies.get('authToken'); // Read token from cookies
        return token ? children : ;
    };
    export default ProtectedRoute;
    
                                    
  • Check is user is already login using js-cookie

    Check if user is already login and open login page then automatically redirect to dashboard page
    Import “useEffect” in login component

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

    Add the following component in inside login component.
    Redirect if already logged in

    useEffect(() => {
        // const token = localStorage.getItem('token');
        const token = Cookies.get('authToken'); // Read token from cookies
        if (token) {
        navigate('/dashboard'); // Redirect to dashboard if token exists
        }
     }, [navigate]);
    
                                    
  • Logout using local storage

    import React from 'react';
    import { useNavigate } from 'react-router-dom';
    
    const Logout = () => {
        const navigate = useNavigate();
        const handleLogout = () => {
            localStorage.removeItem('token'); // Remove the token from localStorage
            alert('You have been logged out!'); // Optional: Notify the user
            navigate('/login'); // Redirect to the login page
        };
        return ;
    };
    
    export default Logout;
    
                                    

    Import above component where you want to add logout button

  • Logout using cookies

    import Cookies from 'js-cookie';
    import { useNavigate } from 'react-router-dom';
    
    const Logout = () => {
        const navigate = useNavigate();
        const handleLogout = () => {
            Cookies.remove('authToken'); // Remove the cookie
            alert('Logged out successfully!');
            navigate('/login');
        };
        return ;
    };
    
    export default Logout;
    
                                    

    Import above component where you want to add logout button