DEV Community

Cover image for Nextjs Oauth2 Integration with AuthAction
AuthAction Developer for AuthAction

Posted on • Edited on

Nextjs Oauth2 Integration with AuthAction

AuthAction is a flexible auth platform for both frontend and M2M apps. It supports OAuth2, social logins, passkeys, and includes user, role, and org management. Scalable up to 1M MAUs for free, it's ideal for startups and enterprises alike.

In this blog, we'll explore how to integrate OAuth2 authentication into a Next.js application using NextAuth.js with AuthAction. It demonstrates how to set up authentication, handle login and logout, and protect routes and API endpoints.

Overview

This application showcases how to configure and handle authentication using AuthAction's OAuth2 service with Next.js. The setup includes:

  • OAuth2 login flow using NextAuth.js with AuthAction as the provider
  • Secure JWT-based session management
  • Protected routes that require authentication
  • Secure API routes with session validation
  • Logout handling with AuthAction's OIDC-compliant logout flow

Prerequisites

Before using this application, ensure you have:

  1. Node.js and npm installed: You can download and install them from nodejs.org.

  2. AuthAction OAuth2 credentials: You will need the following from your AuthAction setup:

    • Tenant Domain
    • Client ID
    • Client Secret
    • Redirect URIs (login and logout)

Installation

  1. Clone the repository (if applicable):
 git clone https://github.com/authaction/authaction-nextjs-example.git cd authaction-nextjs-example 
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies:
 npm install 
Enter fullscreen mode Exit fullscreen mode
  1. Configure your AuthAction credentials:

Create a .env.local file in the root of your project with the following environment variables:

 AUTHACTION_TENANT_DOMAIN=your-authaction-tenant-domain AUTHACTION_CLIENT_ID=your-authaction-client-id AUTHACTION_CLIENT_SECRET=your-authaction-client-secret NEXTAUTH_SECRET=your-secure-random-string NEXTAUTH_URL=http://localhost:3000 
Enter fullscreen mode Exit fullscreen mode

Usage

  1. Start the development server:
 npm run dev 
Enter fullscreen mode Exit fullscreen mode

This will start the Next.js application on http://localhost:3000.

  1. Testing Authentication:
  • Open your browser and navigate to http://localhost:3000.
  • You will be automatically redirected to the AuthAction login page.
  • After successful login, you will be redirected back to the application dashboard.
  • The dashboard displays a welcome message and your profile information.
  • Click the "Logout" button to be logged out and redirected to the specified logout URL.

Code Explanation

Authentication Configuration (pages/api/auth/[...nextauth].ts)

  • Configures NextAuth.js with AuthAction as the OAuth2 provider
  • Uses JWT strategy for session management
  • Handles token refresh and session validation
  • Maps user information from AuthAction to the Next.js session

Protected Pages (/app/dashboard/page.tsx)

  • Uses useSession hook to check authentication status
  • Displays user information when authenticated
  • Shows login prompt when not authenticated
  • Includes logout functionality with proper token handling

API Routes (/app/api/profile/route.ts)

  • Demonstrates server-side session validation
  • Returns user profile information for authenticated requests
  • Implements proper error handling for unauthenticated access

Common Issues

  • Redirects not working:

    • Ensure that the NEXTAUTH_URL matches your application's base URL
    • Verify that the redirect URIs in your AuthAction configuration match exactly
    • Check that your application is running on the port specified in your environment variables
  • Session issues:

    • Make sure NEXTAUTH_SECRET is set to a secure, random string
    • Verify that your AuthAction client secret is correct
    • Check browser console and server logs for any error messages
  • Network Errors:

    • Ensure your application can reach the AuthAction servers
    • Verify that there are no firewall rules or network policies blocking the OAuth2 redirects

Conclusion

Integrating OAuth2 authentication into a Nextjs application using AuthAction and NextAuth.js is a straightforward process. This example helps streamline the setup, offering developers a robust foundation to build secure applications with minimal effort.

If you run into any issues, double-check your configurations and URIs to ensure everything is set up correctly. Happy coding!

Feel free to leave your thoughts and questions in the comments below!

Top comments (0)