43
loading...
This website collects cookies to deliver better user experience
npm install create-next-app authentication
authentication
with the Next.js framework setup for use.npm i next-auth
pages/api
directory. In Next.js, by default all files in this directory are automatically treated as API endpoints, making it simple to use.auth
in the pages/api
folder and within it create a file named […nextauth].js
. In this file. first we add imports for the Next-auth package:import NextAuth from "next-auth";
import GoogleProvider from 'next-auth/providers/google'
export default NextAuth({
providers: [
GoogleProvider({
clientId: "GOOGLE_CLIENT_ID",
clientSecret: "GOOGLE_CLIENT_SECRET",
authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&access_type=offline&response_type=code',
})
],
jwt: {
encryption: true
},
secret: "secret token",
//Callback here
});
...
callbacks: {
async jwt(token, account) {
if (account ?.accessToken) {
token.accessToken = account.accessToken
}
return token;
},
redirect: async (url, _baseUrl)=>{
if (url === '/user') {
return Promise.resolve('/')
}
return Promise.resolve('/')
}
}
});
user
route which we will later create, or any other route back to the home page upon authentication._app.js
file components as shown below:...
import { SessionProvider } from "next-auth/react";
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
export default MyApp;
Sign in
button if the user is not authenticated, else it returns our application. To do this, we modify the index.js
file as shown below:import { useSession, signIn, signOut } from "next-auth/react"
export default function Home() {
const { data: session } = useSession();
if (session) {
return (
<div className={styles.container}>
Welcome user<br />
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}
return (
<div className={styles.container}>
Click to sign into your user account <br />
<button onClick={() => signIn()}>Sign in</button>
</div>
);
}
Session
. If there is no Session
, the Sign in
button is returned, else it returns the Sign out
button.+ Create credentials
in the top-menu bar select OAuth Client id
. If requested to “Configure Consent Screen”, click on this button. On the new page that opens up, select external
for the user type and click on create
. Next, input your app name and email then save and continue. Leave the scope
and Test users
section empty and click on “Save and Continue”.Oauth Client id
. Select “Web application” for the application type. Click on Add URI
and enter http://localhost
. Finally, in the Authorized redirect URIs
section, click Add URI
and in the field provided, key in http://localhost/api/auth/callback/google
. Then create the authentication key. Copy the client ID and the client secret and add it to your application for use.npm run dev
localhost
part of that configuration into your actual host name.protectedpage.js
in the pages
directory and populate it wilth the following code:import { getSession } from "next-auth/react";
import React from "react";
function protectedpage() {
return (
<div>
<h1>Protected Page</h1>
</div>
);
}
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
context.res.writeHead(302, { Location: "/" });
context.res.end();
return {};
}
return {
props: {
user: session.user,
},
};
}
export default protectedpage;
Session
exists to allow access to the page. If Session
does not exist, the user will be redirected to the "
/
"
route which is the home page of the application.user.js
with the following code:import React from "react";
import { useSession } from "next-auth/react";
function user() {
const { data: session } = useSession();
if (!session) {
return <p>You are not logged in.</p>;
}
return <h1>you are logged in</h1>;
}
export default user;
protectedpage.js
file, we can set the header location to return us to the redirect page instead of the home page:...
context.res.writeHead(302, { Location: "/user" });
...