@filiberto
To login with Auth0 in Next.js, you can follow these steps:
1
|
npm install @auth0/auth0-react |
Here's an example of setting up the Auth0 provider in your _app.js
file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { Auth0Provider } from '@auth0/auth0-react'; function MyApp({ Component, pageProps }) { return ( <Auth0Provider domain={process.env.NEXT_PUBLIC_AUTH0_DOMAIN} clientId={process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID} redirectUri={typeof window !== "undefined" && window.location.origin} > <Component {...pageProps} /> </Auth0Provider> ); } export default MyApp; |
Here's an example of using the useAuth0
hook in a component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { useAuth0 } from '@auth0/auth0-react'; function Profile() { const { user, isAuthenticated, isLoading, loginWithRedirect, logout } = useAuth0(); if (isLoading) { return <div>Loading...</div>; } if (!isAuthenticated) { return <button onClick={loginWithRedirect}>Log in</button>; } return ( <div> <img src={user.picture} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> <button onClick={logout}>Log out</button> </div> ); } export default Profile; |
That's it! You have now set up Auth0 login in your Next.js project.