Unlocking the power of NextAuth by incorporating wild card or custom domains into the signin logic

My NextJS application is a multi-tenant SaaS application where each customer can choose to use a subdomain on our site or map their custom domain via CNAME.

This setup allows customers to enable their employees to log in on either the subdomain site or custom domain.

Within the [...nextauth].js file, there is a signIn callback that executes after sign-in:

async signIn({ user, account, profile, email, credentials }) {
 return true
},

In this callback, I need to determine which custom domain or subdomain the user is signing in from and apply specific logic accordingly. However, as the callback does not have access to req headers, how can I retrieve the domain/hostname within it? Depending on the domain, my goal is to permit/block signin or trigger other actions.

Answer №1

Based on your query, the relevant section of the NextAuth documentation that addresses your specific use case can be found here:

https://next-auth.js.org/configuration/initialization#advanced-initialization

If you define a variable in this manner, it will be accessible within the NextAuth options too, as they share the same scope.

import NextAuth from "next-auth"
import { NextApiRequest, NextApiResponse } from "next"

export default async function authenticate(req: NextApiRequest, res: NextApiResponse) {
  const { host } = req.headers; 
  // utilize the value of 'host' in the NextAuth configuration below

  return await NextAuth(req, res, {
    // ...
  })
}

UPDATE:

To access NextAuth configuration in API routes or getServerSideProps, you can follow this pattern:

import { IncomingMessage } from "http";
import { NextApiRequest, NextApiResponse } from "next";
import NextAuth, { NextAuthOptions } from "next-auth";

export function authenticationOptions(req: IncomingMessage): NextAuthOptions {
  const { host } = req.headers;

  return {
    // ...
  }
};

export default async function authenticate(req: NextApiRequest, res: NextApiResponse) {
    return await NextAuth(req, res, authenticationOptions(req));
}
import { getServerSession } from "next-auth";
import { NextApiRequest, NextApiResponse } from "next";
import { authenticationOptions } from "./auth/[...nextauth]";

export default async function post(req: NextApiRequest, res: NextApiResponse) {
  const session = await getServerSession(req, res, authenticationOptions(req));
  // ...
}

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

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

Utilize Vue-cli 3.x to load static resources

In my vue-cli 3 project, I have organized the static assets in the public directory. When compiled and built on localhost, all assets load successfully, except for some images not appearing in the browser. Despite guyana-live-logo.png, slide-1.jpg, and 97 ...

Adding a character at the current cursor position in VUE JS

My quest for inserting emojis in a textarea at the exact cursor position has led me to an extensive search on Vue JS techniques. However, most resources available online provide solutions using plain Javascript. Here is the code snippet I am working with: ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Saving, displaying, and removing a JSON document

As someone new to the world of JavaScript, I am encountering an issue with JavaScript and AJAX. I am aiming to create a function that allows me to add new elements with unique indexes. After saving this information to a JSON file, I want to display it on a ...

Using HTML Select field to make ajax calls to web services

When working with modals that contain forms to create objects for database storage, there is a Select field included. This is the code snippet for the Select field: <div class="form-group" id=existingUser> <label>Username</label> < ...

Are there alternative methods for incorporating react-multi-carousel in a project utilizing NEXT.js and React/Typescript?

I installed the react-multi-carousel module and configured a simple carousel, but it's not functioning properly. The issue seems to be related to the absence of <li> tags. Here is the HTML that was rendered: <ul class="react-multi-caro ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

"Utilize Node.js to generate a nested array structure with groupings

Here is an array data that I have: [ { tempId: 1, nik: '11002', employeeName: 'Selly Amaliatama', basic_salary: 3500000, id_component: 'AD0128114156', componentName: 'Tunjangan Maka ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing th ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Is it possible for the versions in the package.json file to be altered

I've made updates to my package.json file - all packages are listed as follows: "dependencies": { "@apollo/client": "3.6.4", "bootstrap": "4.6.2", "graphql": "16.5.0" } ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

Is there a method I can use to merge similar functions in redux-toolkit?

Is there a way to streamline setting the cart state to true and others to false in one action? For example, if payload == "cart, true", then set cart to true and all other states to false. const initialState = { cart: false, addNewAddress: false, ad ...