Unlock the full potential of NextAuth by incorporating wildcard and custom domains for enhanced user

I am currently developing a NextJS application that functions as a multi-tenant SaaS platform.

Within the app, each customer has the ability to either utilize a subdomain on our site or map their own custom domain via CNAME.

My goal is to enable our customers to permit their employees to log in on their designated subdomain or custom domain.

export const authOptions: NextAuthOptions = {
  // Configure one or more authentication providers
  providers: [
     EMAIL PROVIDER
    // ...add more providers here
  ],
  pages: {
    signIn: `/login`,
    verifyRequest: `/verify`,
  },
  adapter: PrismaAdapter(prisma),
  callbacks: {

  },
  cookies: {
    sessionToken: {
      name: 'next-auth.session-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    },
    callbackUrl: {
      name: 'next-auth.callback-url',
      options: {
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    },
    csrfToken: {
      name: 'next-auth.csrf-token',
      options: {
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    }
  }  
}

export default NextAuth(authOptions)

The existing setup of using '.mysaas.com' for the domain cookie allows for functionality with subdomains successfully.

However, there is an issue when it comes to making it work seamlessly with a custom domain mapped to a subdomain. How can this be resolved?

If it were possible to dynamically set the cookie domain based on the actual domain visited, such as changing from .mysaas.com to .mycustomdomain.com when accessed from the custom domain, then the problem would be solved.

Unfortunately, I have not been able to find a way to achieve setting the cookie domain dynamically. Any suggestions or assistance would be greatly appreciated.

Answer №1

To fix the issue with NextAuth using the current domain by default, simply eliminate the domain property from your NextAuth configuration.

Answer №2

For your specific requirements, it is necessary to enable login from both subdomain and your custom domain in the configuration settings. This task can be easily accomplished by adjusting the cookie section.

export const authOptions: NextAuthOptions = {
  // Customize authentication providers as needed
  providers: [
    // EMAIL PROVIDER
    // ...add more providers here
  ],
  pages: {
    signIn: `/login`,
    verifyRequest: `/verify`,
  },
  adapter: PrismaAdapter(prisma),
  callbacks: {
    session: async (session, user) => {
      // Define the session's domain based on incoming request
      session.domain = session?.cookies?.nextauth_url
        ? new URL(session.cookies.nextauth_url).hostname
        : undefined;

      return Promise.resolve(session);
    },
  },
  cookies: {
    sessionToken: {
      name: 'next-auth.session-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false,
      },
    },
    callbackUrl: {
      name: 'next-auth.callback-url',
      options: {
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false,
      },
    },
    csrfToken: {
      name: 'next-auth.csrf-token',
      options: {
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false,
      },
    },
  },
};

export default NextAuth(authOptions);

If you require any further assistance, please feel free to reach out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Many mistakes encountered while trying to import web3 into app.js

Encountered 9 errors while trying to import web3 into App.js import React from "react"; import Web3 from "web3"; function App() { return ( <div className="App"> <h1>TEST APP</h1> </div> ...

A tutorial on creating a fixed header in Next.js using the useEffect hook

Currently, I am developing a website using next.js. My goal is to create a fixed header that remains in place as the user scrolls down the page. Although I am still getting familiar with the concept of useEffect, I decided to try an experiment: export fun ...

Is it possible to locate and substitute content with a variable in Visual Studio Code?

In my dataset, there are some numbers that are too large to be int values (>2147483647). When they exceed this limit, they are recorded as "price_amount" : { "$numberLong" : "3900000000" }. However, I have updated the data ...

The placeholder text in the matInput field is not being displayed

As a newcomer to Angular, I am facing a challenge that has left me unable to find a solution. Below is the code snippet in question: <mat-form-field> <input matInput placeholder="ZIP" style="color:red;"> </mat-form-field& ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

guide on utilizing nested loops and arrays in Vue.js

The results returned by the controller query are as follows: date: {2020-09-24: {work_hours: 7}, 2020-09-30: {work_hours: 8}} 2020-09-24: {work_hours: 7} 2020-09-30: {work_hours: 8} Within my Vue component, I am attempting to use ne ...

How can you use JQuery to assign a single function as an onClick handler for multiple radio buttons?

I have a custom function named handleOnClickRadio(i, j);, and multiple radio buttons with the IDs in the format of id="something-radio[i][j]". These radio buttons are all contained within a table labeled "bigtable". Is there a way to link the function han ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

Utilizing JavaScript to access and present results from a PHP file located on a separate server

UPDATE I have set the header of my php file as shown below: header("Access-Control-Allow-Origin: *"); Currently, this is the error I am seeing in my browser: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Heade ...

When lines are added to a file in Node.js, the content is written in a haphazard sequence

I've encountered an issue with the code I wrote where the header line is not consistently at the top. It seems to randomly appear on the second or third line instead. I've tried troubleshooting multiple times without success, so any help would be ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Update the Div content with animation on the change

I have mastered the art of refreshing a DIV element, but now I am looking to take it up a notch by incorporating an animation into the transition. The idea is that when a user approves an offer, the div containing a series of boxes should elegantly 'm ...

Accessing Google Sheets with the default login information

I have data stored in Google sheets and I am utilizing the Sheets API for Node.js to retrieve this data. To authenticate, I am using Service Account JSON to create a JWTClient. Accessing the data through the Sheets API is functional and everything is runn ...

Nested jquery tabs

Similar Question: Unable to get jquery tabs nested I am trying to create a nested tab, but haven't found a satisfactory solution through my research. Can anyone provide me with some guidance? I have limited experience in JavaScript or jQuery prog ...

How can I allow the background image of a div to be edited in the Experience Editor with Sitecore NextJS?

I have designed a custom component in Sitecore Next Js React that serves as a full-width banner. I am looking to add an image as the background of the parent dive, and this image should be easily editable through the experience editor. Can anyone provide ...

Fundamental JavaScript associative object

I am working with an array filled with various items. let items = {'A', 'A', 'A', 'B', 'B', 'C'} My goal is to generate a new array that shows the count of each item present in the original arra ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...

Retrieve tag, custom taxonomy, and attachment information using the get_pages function

Currently, I have implemented code that retrieves all pages submitted by the currently logged-in author using the get_pages function. The retrieved result is then passed to Javascript via Ajax. Everything functions as expected, and the correct pages are be ...

Choose2 - Dynamic search with auto-complete - keep track of previous searches

Currently, I am utilizing Select2 version 3.5.1 and have successfully implemented remote data loading with the plugin. However, I have a query regarding enhancing the search functionality. Below is a step-by-step explanation of what I aim to achieve: Cre ...

Validation of HTML forms through JavaScript

I'm working on form validation and struggling with implementing preg_match check from a variable. Currently, I can validate empty fields successfully, but that's not sufficient. Any suggestions on how to proceed? var pattern = /([a-zA-Z0-9]|[a-z ...