/my-nextjs-app
├── /contexts│
└── UserContext.tsx
├── /pages│
├── _app.tsx│
└── index.tsx
├── /container
│ └── HomeContainer.tsx
├── /utils
│ └── oktaConfig.ts
├── /styles
│ └── globals.css
└── package.json
HomePage Component (/pages/index.tsx):
// /pages/home.tsx
import React, { useEffect } from "react";
import { useOktaAuth } from "@okta/okta-react";
import HomeContainer from "@/container/HomeContainer";
const HomePage: React.FC = () => {
const { authState, oktaAuth } = useOktaAuth();
useEffect(() => {
const checkAuth = async () => {
if (authState && !authState.isAuthenticated) {
await oktaAuth.signInWithRedirect();
}
};
if (authState !== null) {
checkAuth();
}
}, [authState, oktaAuth]);
if (authState === null) {
return <div>Loading authentication state...!!</div>;
}
if (!authState.isAuthenticated) {
return <div>Redirecting to login...</div>;
}
return (
<div>
<HomeContainer/>
</div>
);
};
export default HomePage;
MyApp Component (/pages/_app.tsx):
// /pages/_app.tsx
import { AppProps } from "next/app";
import { OktaAuth } from "@okta/okta-auth-js";
import { Security, useOktaAuth } from "@okta/okta-react";
import { useRouter } from "next/router";
import { oktaConfig } from "../utils/oktaConfig";
import "../styles/globals.css";
// Initialize Okta Auth
const oktaAuth = new OktaAuth(oktaConfig);
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
// Restore the original URI after login
const restoreOriginalUri = async (_oktaAuth: OktaAuth, originalUri: string) => {
router.replace(originalUri || "/");
};
return (
<Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
<Component {...pageProps} />
</Security>
);
}
export default MyApp;
`Problem Description: When I run the application, the oktaAuth instance appears to be undefined in the HomePage component. I am trying to check if the user is authenticated and redirect to the Okta login page if not, but I’m not sure if I’m implementing the Security wrapper correctly or if I’m missing something in the setup.
"@okta/okta-auth-js": "^7.8.1",
"@okta/okta-react": "^6.9.0",
"next": "^14.1.2",
"next-auth": "^4.24.5",
How can I properly pass the oktaAuth instance to the HomePage component? Are there any best practices I should follow when integrating Okta with Next.js? Is there anything else I might be missing in my setup?