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

Reduce the size of static-generated assets using Next.js

After creating static files with Next js, I uploaded them to Amazon S3. However, I noticed that the generated .js and .css files are not compressed as needed for Google Analytics. The issue is: Text-based resources must be served with compression (gzip, d ...

The POST request functions smoothly in Postman, however, encounters an error when executed in node.js

Just recently I began learning about node.js and attempted to send a post request to an external server, specifically Oracle Commmerce Cloud, in order to export some data. Check out this screenshot of the request body from Postman: View Request Body In Pos ...

JavaScript - undefined results when trying to map an array of objects

In the process of passing an object from a function containing an array named arrCombined, I encountered a challenge with converting strings into integers. The goal is to map and remove these strings from an object titled results so they can be converted i ...

Error encountered in vscode: certain files failed to transfer during rsync process (code 23)

Recently, I've been facing an issue with my EC2 deployment using rsync. Everything was working smoothly until about a week ago when I started encountering the error mentioned below. It seems to be related to IOS deployment, although I am deploying a ...

The computed function in Vue.js fails to provide a return value

I'm currently experimenting with a basic to-do list using vue.js. My goal is to calculate the total sum of all price values within an array. I created a small function under computed, but it seems like something isn't working correctly. Here&apos ...

What's the best way to align three images in a row?

I am having trouble centering three social media icons next to each other. I can't seem to figure out the proper way to do it. https://i.stack.imgur.com/Zf5p9.png <div class="maintext flipInX animated"> <div class="socials wow bounce an ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Regular expression that matches a string with optional leading and trailing spaces and a hyphen in the middle

I need help creating a JavaScript regex that can match strings like the examples provided. The string may have whitespace at the front, back, or both but not within the string itself. Examples: 'Z5LW-KRT2' MATCH ' Z5LW-krt2' ...

What is preventing Javascript from executing a function when there is an error in another function?

Can you explain why a JavaScript function fails to run if there is an error in another function? Recently, I encountered an issue on my HTML page where the alert from the popup1() function would not load. It turns out the problem stemmed from an error in ...

Incorporating a HTML layout with a JS backdrop

I have successfully implemented a JavaScript background and now I want to apply this background across all my PHP files. The issue is that the HTML code either overlaps with the JS content or appears behind it. How can I resolve this? Below is the JS fil ...

What is the solution to fixing the Vue 2 error when using Node 12?

Issue with Node 12: It seems that there is an error related to the node-sass library in Node 12. Error message from Node: node-pre-gyp ERR! node -v v12.1.0 node-pre-gyp ERR! node-pre-gyp -v v0.10.3 node-pre-gyp ERR! not ok ...

Refreshing HTML content using event delegation in JavaScript

Currently, I am attempting to dynamically load additional HTML content onto my webpage when a button is clicked. Here is the code that I have implemented so far: Main HTML Code: <div class="row" id="gallery-wrapper" > <di ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Encountering a problem when looping through a JSON response

After making an Ajax call, I received the JSON response below. studentList: { "currentStudent":0, "totalStudent":11, "studentDetails": [{ "adId":1, "adName":"BMB X5", "sfImage":{ "imageName":"Desert", "image ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

Is it possible to create a dynamic <hr /> using Flexbox?

In the midst of working on my application, I managed to achieve a simple layout. However, there is one peculiar requirement that has been eluding me for the past 2 days and now I find myself in need of assistance. Here is the current HTML code I am workin ...

Transferring data from a callback function within a component to a different component

I am currently utilizing the giphy-api module in Node.js and I need to transfer this data to React. Within my setup, I have two key components: The first component, Api.js, effectively connects with Node.js and returns a callback containing all of the AP ...

Node JS: Despite modifying the URL, the response remains unchanged

My attempt to log in to teeSpring.com and retrieve a response from another URL using a login cookie seems to be causing an issue. Upon logging into teeSpring.com, the dashboard details are returned. However, when I try to make a GET request to the second U ...

I would greatly appreciate some guidance on asp.net and javascript

I am just starting out with JavaScript and facing some challenges. Currently, I'm struggling to develop a Mouseover and mouseout script. Here is my ASPX code: <div> <div id="div_img" style="height: 300px; width: 300px; border: solid 1p ...

How can you use jQuery to target a textbox based on its value that includes quotation marks?

Dealing with a JavaScript string that includes a quote mark can cause some difficulties. For example, strings like Don't click this checkbox or He said "hi" pose unique challenges when trying to find an exact match in a checkbox value. Consider the H ...