Logo
Home

How I setup Authentication in 10 minutes in Next.js?

some good alt text
Web DevelopmentTechnology

About the author

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

profile

Jasneet Singh Sawhney

4/6/2021

Setting up authentication is the most vital and arduous task in the complete frontend journey. The intricacies and nuances accrue a long list of base and edge cases that one can easily skip some of them and invite hackers to do weird stuff with your application.

Hence, keeping this thing in mind, I first thought of going with Auth0 service but their free tier was limited and the pricing was also not cheap. Though I have heard a lot about their service, still I wasn't ready for this.

So thought of building it again. Rolled up my sleeves and started reading about sessions, cookies, and JWTs (whoever you are, you have to revise the core concepts before diving into something - you should spend major time sharpening your ax, then cut the tree).

In my pursuit of learning from the best blogs out there, I stumbled upon a blog by logrocket which talks about Next-Auth. This led me to give it a shot and voila! my authentication setup was ready under 10 minutes with the global session that I could use anywhere and they also handle all the edge cases by themselves. I just did the following steps:

yarn add next-auth

After installing the libarary, I setup the boilerplate code for google oauth and manual auth. First let's setup the API in /api/auth/[...nextauth].js

import NextAuth from 'next-auth' import Providers from 'next-auth/providers'

export default NextAuth({

providers: [

// OAuth authentication providers

Providers.Google({

clientId: process.env.GOOGLE_ID,

clientSecret: process.env.GOOGLE_SECRET }),

// Sign in with passwordless email link

Providers.Email({

server: process.env.MAIL_SERVER,

from: '<no-reply@example.com>'

}), ],

// SQL or MongoDB database (or leave empty) database: process.env.DATABASE_URL

}) 

Now, move to the client, make a page component and add:

import { useSession, signIn, signOut } from 'next-auth/client'

export default function Component() {

const [ session, loading ] = useSession()

if(session) {

return

<> Signed in as {session.user.email}

<br/>

<button onClick={() => signOut()}> Sign out </button>

</>

} return

<> Not signed in <br/>

<button onClick={() => signIn()}>Sign in</button>

</> } 

Now it will work fine, but will flicker on each route change, as session is not global right now. For the same, we need to add provider into our app.js

// pages/_app.js

import { Provider } from 'next-auth/client'

export default function App({ Component, pageProps }) {

return (

<Provider session={pageProps.session}>

<Component {...pageProps} />

</Provider>

)}

Great!! We are done. 

But it will work fine on localhost, not on production. On production, using Google OAuth will first redirect to the vercel app and then sign in over there. To fix this issue, inside vercel add an environment variable :

NEXTAUTH_URL=https://example.com

Okay, we are good to go now.

To make out authentication more secure, one update I have done recently is started using JWT token, so in your auth api you just need to add :

jwt: {

secret: process.env.JWT_SECRET,

}

Also, you want to salt everything for your nextauth.js so we need to add one secret as well

secret: {process.env.AUTH_SECRET}