49
loading...
This website collects cookies to deliver better user experience
yarn
, but you can use npm
too.yarn create next-app next-oauth-demo
next-auth
which will help us implement authentication very easily.
yarn add next-auth
next-auth
. Create a new file exactly like this in having the path: pages/api/auth/[...nextauth].js
./api/auth/
to let next-auth
handle it.[...nextauth].js
file and add some configuration.// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default (req, res) =>
NextAuth(req, res, {
providers: [
Providers.GitHub({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
],
debug: process.env.NODE_ENV === "development",
secret: process.env.AUTH_SECRET,
jwt: {
secret: process.env.JWT_SECRET,
},
callbacks: {
async redirect(url, baseUrl) {
return "/";
},
},
});
OAuth Apps
tab click on New OAuth App
.Application name
and the Application description
keep everthing else the same as shown in the below picture.Register application
. Now, you'll be greeted with a screen with your Client ID
. Click on the button to generate client secret..env.local
and paste the tokens here.AUTH_SECRET
and JWT_SECRET
as well. Just hadjhjasdasdjasruhsfdghfgsdfsd
away at your keyboard!next-auth
's APIs.pages/index.js
page as a login page. Paste the following code in itimport React from "react";
import { useSession, signIn, signOut } from "next-auth/client";
export default function Home() {
const [session] = useSession();
return (
<div>
<h1>Github OAuth Demo</h1>
{!session ? (
<>
<button onClick={() => signIn("github")}>
Sign in with Github
</button>
</>
) : (
<>
<p>
Not {session.user.name || session.user.email}? Then
Logout and login again
</p>
<button onClick={signOut}>Logout</button> <br />
</>
)}
</div>
);
}
yarn dev
Signin with GitHub
button to be signed in!next-auth
, you can check out the docs here.