How to redirect after after login using amplify?

0

I need to redirect user after login but i am not able to do.

import React from "react";
import { Authenticator } from "@aws-amplify/ui-react";
import "@aws-amplify/ui-react/styles.css";
import Wrapper from "../../../element-components/base-components/Wrapper";

export const AmplifyHostedUI: React.FC = () => {
	const component = {
		SignIn: {
			Header() {
				return <div className="flex text-xl font-bold pb-4">Log-In</div>;
			},
		},
	};

	return (
		<Wrapper>
			<div className="flex h-fit w-fit">
				<Authenticator hideSignUp components={component}></Authenticator>
			</div>
		</Wrapper>
	);
};

export default AmplifyHostedUI;

how to redirect user after they login from /login to /dashboard

2 Answers
0

Hello MD,

To redirect a user after they log in using the AWS Amplify Authenticator, you can use the onStateChange prop to listen for changes in the authentication state and then conditionally redirect the user to the desired location (e.g., /dashboard). Here's how you can achieve this:

  1. Import the necessary components and libraries:
import React, { useEffect, useState } from "react";
import { Authenticator } from "@aws-amplify/ui-react";
import { Auth } from "aws-amplify"; // Import Auth from AWS Amplify
import "@aws-amplify/ui-react/styles.css";
import Wrapper from "../../../element-components/base-components/Wrapper";
import { useHistory } from "react-router-dom"; // Import useHistory from react-router-dom
  1. Create your functional component:
export const AmplifyHostedUI: React.FC = () => {
  const component = {
    SignIn: {
      Header() {
        return <div className="flex text-xl font-bold pb-4">Log-In</div>;
      },
    },
  };

  const history = useHistory(); // Create a history object to manage navigation

  // State to track the current authentication state
  const [authState, setAuthState] = useState<string | undefined>(undefined);

  useEffect(() => {
    // Add an event listener to handle changes in authentication state
    const listener = async (state: string, data: any) => {
      if (state === "signedin") {
        // Redirect the user to the /dashboard route upon successful sign-in
        history.push("/dashboard");
      }
      setAuthState(state);
    };

    // Subscribe to the event
    Auth.currentAuthenticatedUser()
      .then((user) => {
        setAuthState("signedin");
      })
      .catch((err) => {
        setAuthState("signIn");
      });

    const subscription = Auth.subscribe(listener);

    return () => {
      // Unsubscribe from the event when the component is unmounted
      subscription.unsubscribe();
    };
  }, [history]);

  return (
    <Wrapper>
      <div className="flex h-fit w-fit">
        <Authenticator hideSignUp components={component} authState={authState}></Authenticator>
      </div>
    </Wrapper>
  );
};

export default AmplifyHostedUI;

In this code:

  • We import the useHistory hook from react-router-dom to manage navigation.
  • We create a history object to interact with the router.
  • We use the useEffect hook to add an event listener that listens for changes in the authentication state.
  • When the state changes to "signedin" (i.e., the user successfully signs in), we use history.push("/dashboard") to redirect the user to the /dashboard route.
  • The authState prop is set to the current authentication state to display the appropriate UI components.

With this setup, after the user successfully logs in, they will be redirected to the /dashboard route.

profile picture
answered 7 months ago
  • The above code not working ,useHistory not available on react-router-dom also Auth class does not have subscribe method

0

Hi guys,

I solved using useNavigate (React Router >= 6 ) instead of useHistory(). And Amplify Hub instead of Auth.subscribe().

Tested with

  • React 18.2.0
  • react-router-dom 6.10.0
  • @aws-amplify/ui-react 5.1.1
//
// index.tsx
//
import React from "react";
import ReactDOM from "react-dom/client";

import { Amplify } from "aws-amplify";
import { HashRouter as Router } from "react-router-dom";

import App from "./App";

import awsconfig from "./aws-exports";
import "@aws-amplify/ui-react/styles.css";

Amplify.configure(awsconfig);

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement,
);
root.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
);

//
// App.tsx
//
import { FC, useEffect } from "react";

import { Authenticator } from "@aws-amplify/ui-react";
import { Hub } from "aws-amplify";
import { Link, Routes, Route, useNavigate } from "react-router-dom";

const App: FC = () => {
  const navigate = useNavigate();

  useEffect(() => {
    Hub.listen("auth", (data) => {
      if (data?.payload?.event === "signIn") {
        navigate("/protected");
      }
    });
  }, []);

  return (
    <Authenticator>
      {({ signOut, user }) => {
        return (
          <>
            <Link to="/protected/about">About</Link>
            <button onClick={signOut}>Sign out</button>

            <Routes>
              <Route
                element={<h1>Protected about</h1>}
                path={"/protected/about"}
              />
              <Route element={<h1>Protected</h1>} path={"/protected"} />
            </Routes>
          </>
        );
      }}
    </Authenticator>
  );
};

export default App;

Hope this could help

profile picture
answered 7 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions