Unlock Secure Client-Side Authentication in Next.js with Auth.js

What is Auth.js?

Auth.js, previously known as NextAuth.js, is a robust and flexible authentication library designed to synchronize with a vast list of OAuth services, offering full support for passwordless sign-in. This library can be used with or without a database, providing default support for popular databases like MySQL, MongoDB, PostgreSQL, and MariaDB.

Getting Started with Auth.js

To set up client-side authentication in a Next.js application using Auth.js, follow these steps:

  1. Create a new Next.js application: Run npx create-next-app my-app to create a new Next.js app.
  2. Install Auth.js: Install Auth.js using npm install @auth0/nextjs-auth0 or yarn add @auth0/nextjs-auth0.
  3. Configure Auth.js: Create an auth.ts file in the project root and configure Auth.js for GitHub authentication.

// auth.ts
import NextAuth from '@auth0/nextjs-auth0';

export default NextAuth({
  // Configure GitHub OAuth
  providers: [
    {
      id: 'github',
      type: 'oauth',
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    },
  ],
});

Authenticating with GitHub OAuth

To authenticate with GitHub OAuth, create a catch-all dynamic route that responds to all relevant Auth.js API routes. Then, create a signIn function to initiate the sign-in process.


// pages/api/auth/[...nextauth].js
import NextAuth from '@auth0/nextjs-auth0';

export default NextAuth({
  async signIn(req, res) {
    // Initiate GitHub OAuth sign-in process
    return await NextAuth.signIn('github', req, res);
  },
});

Querying the Current User Session

Use the useSession Hook to fetch the logged-in user’s information and display it in the application. You can also use the auth call to query the user’s session on the server.


// components/UserInfo.js
import { useSession } from '@auth0/nextjs-auth0';

function UserInfo() {
  const { data: session, status } = useSession();

  if (status === 'authenticated') {
    return (
Welcome, {session.user.name}!Email: {session.user.email}


    );
  }

  return 

You are not logged in.

;
}

Magic Link Authentication with Auth.js

To implement magic link authentication, configure the Auth.js session strategy to jwt and set up a database to store and manage unique tokens sent to users for authentication. Then, create a custom login page and send magic links using the sendVerificationRequest function.


// pages/api/auth/magic-link/[...nextauth].js
import NextAuth from '@auth0/nextjs-auth0';

export default NextAuth({
  async sendVerificationRequest(req, res) {
    // Generate and send a magic link to the user
    const token = await NextAuth.generateMagicLinkToken(req.body.email);
    await sendMagicLinkEmail(req.body.email, token);
    return res.status(200).json({ message: 'Magic link sent!' });
  },
});

Creating Protected Routes with Auth.js

Protect routes in your application using Server Components or middleware. In Server Components, check if a user session exists and redirect unauthenticated users to the sign-in page. In middleware, use the matcher property to define the routes to which the middleware function should be applied.


// middleware/auth.js
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from '@auth0/nextjs-auth0';

export default async function authMiddleware(req: NextApiRequest, res: NextApiResponse) {
  const session = await getSession(req, res);
  if (!session) {
    return res.redirect('/api/auth/signin');
  }
  return NextApiResponse.next();
}

Centralizing Authentication Logic

By using middleware, you can centralize the logic for protecting routes and make it more maintainable.


// next.config.js
module.exports = {
  // Add auth middleware to protected routes
  middleware: [authMiddleware],
};

Leave a Reply