DEV Community

Larson
Larson

Posted on

Shout out to next-auth

For my new project Tuxedo Mask, hide your E-Mail Address I switched to next-auth. And what should I say? That's a library, I realy like. You can clearly say, they had the developer in mind. What did I say? developer? Even my unborn child can configure it.

Here an example:

In this little "game" https://looty.vercel.app, looty the lootbox.

I have this code in the api/auth/[nextauth].js (which is the entrypoint for next-auth):

import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
import DiscordProvider from 'next-auth/providers/discord';

export default NextAuth({
    providers: [

        GithubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
            // https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
            scope: 'read:user',
        }),
        DiscordProvider({
            clientId: process.env.DISCORD_APP_ID,
            clientSecret: process.env.DISCORD_APP_SECRET,
        }),
    ],
    secret: process.env.SECRET,

    session: {
        strategy: 'jwt'
    },
    callbacks: {
        async signIn({user, account, profile, email, credentials}) {
            return true;
        },
        // async redirect({ url, baseUrl }) { return baseUrl },
        // async session({ session, token, user }) { return session },
        // async jwt({ token, user, account, profile, isNewUser }) { return token }
    },

    theme: {
        colorScheme: 'light',
    },

    debug: false,
});

Enter fullscreen mode Exit fullscreen mode

And finally in the _app.js

import {SessionProvider} from 'next-auth/react';
import '../styles/globals.css';

function MyApp({Component, pageProps}) {
    return (
        <SessionProvider>
            <Component {...pageProps} />
        </SessionProvider>
    );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

then you can work with useSession for example

import {useSession} from 'next-auth/react'
const {data: session, status} = useSession();
Enter fullscreen mode Exit fullscreen mode

And thats mostly it. For this little guy it worked perfectly. next-auth has tons of configurations and you can even add your own authentication layer.

When working with authentication for nextjs please consider to use next-auth and support this project.

They have a lot of providers and you can use your own Database too.

https://github.com/nextauthjs/next-auth
https://www.npmjs.com/package/next-auth

Thanks.

Top comments (0)