Configuring NextAuth in Next.js 13.4

In this guide, we will set up NextAuth for authentication in a Next.js 13.4 project using the Discord provider. This configuration will help you manage user sessions securely with JWT strategy.

Step 1: Install Dependencies

Make sure you have NextAuth and the Discord provider installed in your project:

npm install next-auth next-auth/providers/discord

Step 2: Create the Authentication Route

Create a file named route.ts in your app/api/auth/[...nextauth] directory. This file will handle authentication requests.

import NextAuth, { AuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";

// Define the authentication options
export const authOptions: AuthOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.CLIENT_ID as string,
      clientSecret: process.env.CLIENT_SECRET as string,
    }),
  ],
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET,
};

// Create the NextAuth handler
const handler = NextAuth(authOptions);

// Export the handler for GET and POST requests
export { handler as GET, handler as POST };

Step 3: Environment Variables

Ensure that you have the following environment variables set in your .env file:

CLIENT_ID=your_discord_client_id
CLIENT_SECRET=your_discord_client_secret
NEXTAUTH_SECRET=your_secret_key

Step 4: Troubleshooting Type Errors

If you encounter a type error similar to the following when running npm run build:

Type error: Type 'AuthOptions' is not assignable to type 'never'.

This usually indicates an issue with TypeScript not recognizing the AuthOptions type correctly. Ensure that your TypeScript configuration is set up properly and that you are using compatible versions of Next.js and NextAuth.

Conclusion

By following these steps, you should have a working NextAuth configuration with Discord as the authentication provider. If you run into issues, double-check your environment variables and TypeScript settings.