Error in redirection while deploying Auth.js (v5) within a Docker container in a Next.js application

Has anyone successfully integrated the latest version of Auth.js into a production environment with Docker? I am currently utilizing the t3-stack (tRPC, Auth.JS, Prisma, Next.JS).

I attempted to upgrade to the beta version with the Prisma Adapter, but encountered an issue where signing in through any provider redirects to the Docker internal host, which is 0.0.0.0. I'm unsure if this problem lies within Auth.js or Next.JS itself.

Setting the environment variables NEXTAUTH_URL and/or AUTH_URL to the production URL seems to correctly set the redirect URL on the provider page. However, after successfully signing in, the redirection still leads to 0.0.0.0.

(The application and authentication flow worked fine before upgrading to Auth.js)

In my Dockerfile, I've configured the following according to the official Next.JS documentation:

EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

This is what my Auth.js configuration looks like:

export const {
  handlers: { GET, POST },
  auth,
} = NextAuth({
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
    signOut: "/auth/logout",
    verifyRequest: "/auth/verify-request",
  },
  callbacks: {
    signIn({ user, email }) {
      // If email provider is used, only allow users with a specific email domain
      if (email?.verificationRequest) {
        return !isFakeEmail(user.email!, false);
      }

      return true;
    },
    session: ({ session, user }) => ({
      ...session,
      user: {
        ...session.user,
        id: user.id,
        role: user.role,
        subscribedTill: user.subscribedTill,
      },
    }),
  },
  adapter: PrismaAdapter(db),
  providers: [
    EmailProvider({
      server: env.EMAIL_SERVER,
      from: env.EMAIL_FROM,
      maxAge: 5 * 60, // valid for 5 minutes
    }),
    DiscordProvider({ allowDangerousEmailAccountLinking: true }),
    GitHubProvider({ allowDangerousEmailAccountLinking: true }),
  ],
  trustHost: true, // Notice trustHost being set to true
});

I have experimented with different combinations of excluding NEXTAUTH_URL / AUTH_URL or using them together in my .env file.

Currently, setting

AUTH_URL="https://my-production-url.com/api/auth"
yields the described behavior (correct oauth redirect path, incorrect redirect upon successful oauth sign-in).

The package versions I am currently using are:

"@next-auth/prisma-adapter": "^1.0.7",
"next-auth": "^5.0.0-beta.15",
"next": "14.1.0",

Is there possibly a missing variable that could be causing this issue? I came across a related discussion on GitHub without a concrete solution: https://github.com/nextauthjs/next-auth/discussions/8449

Answer №1

After struggling with this issue for some time, I was finally able to resolve it (at least for my application).

Here is the configuration that worked for me:

In the Dockerfile:

EXPOSE 3000 
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

In the .env file:

AUTH_SECRET=secret
AUTH_TRUST_HOST=true
AUTH_REDIRECT_PROXY_URL=https://your-prod-domain/api/auth

In auth.ts:

 callbacks: {
    async redirect({ url, baseUrl }) {
      //do other stuff or redirects here
      return url;
    },
}

This setup has been working well for my app as it always redirects to the homepage after login.

I hope you can benefit from this configuration as well.

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

`Is there a way to resolve the getStaticProps type issue in Next.js while utilizing InferGetStaticPropsType?`

I'm puzzled by an error that occurred with post props. The error message reads as follows: Property 'body' does not exist on type 'never'. https://i.stack.imgur.com/zYlxc.png Even when I specify the type, can there still be an er ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

Is there a way for me to modify the status code of a Next.js page?

Is it possible to set the status code 503 for specific pages in my Next app? Currently, every page returns a status code of 200, even if they are undefined. How can I change this? Just to clarify, when I refer to the status code, I mean the status of the ...

Display clickable buttons beneath the Material-UI Autocomplete component

I want to place buttons ("Accept" and "Cancel") below the MUI Autocomplete element, and I am trying to achieve the following: Limit the Autocomplete popover height to display only 3 elements. To accomplish this, pass sx to ListboxProps Ensure that the b ...

TSX: Interface Definition for Nested Recursive Array of Objects

I'm having trouble making my typescript interface compatible with a react tsx component. I have an array of objects with possible sub items that I need to work with. Despite trying various interfaces, I always run into some kind of error. At the mome ...

Obtaining the Hostname for server-side fetch in NextJS13 component on Vercel platform

When working with a server-side component in NextJS13 and using the fetch function, the code typically looks like this: fetch("http://localhost:3000/api/test") The endpoint URL ("/api/test") can vary depending on the environment in which it is d ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

The createContext function mistakenly used the default value instead of the value that was supposed to

When I import and use a context that allows child components to setTheme, the useContext hook returns the default value instead of the passed value. What could be causing this issue and how can I resolve it? I apologize for any poor English in my explana ...

An ambient module will not be successfully resolved through a relative import operation

As per the typescript documentation (https://www.typescriptlang.org/docs/handbook/module-resolution.html): A relative import is resolved in relation to the importing file and does not resolve to an ambient module declaration. However, it also states: ...

Ensuring type safety in React using TypeScript

Within the code snippet below, I have specified that setLocale should be passed a value of type Locale through LocaleContextValue. However, why does the setLocale function not throw an error if no value is provided as a parameter? Even when I change it t ...

Upon execution with "next," Next.js fails to capture console.log or console.error messages

Within my server.js file, I have these logs: console.info("LOOGGGGGSSSS") console.warn("LOOGGGGGSSSS") console.log("LOOGGGGGSSSS") console.error("LOOGGGGGSSSS") The script in my package.json is as follows: "scripts": { "dev": "next", " ...

NEXT JS 13 experiencing an infinite loop when using State, encountering an error with Params, and facing issues with hook definition

Currently, I am in the process of developing a shopping cart using NEXT JS and encountering several issues within my code. To begin with, I have established a route [product]/[productitems] within the apps folder. In the page.tsx file of [productitems], I ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Best practices for implementing Django backend authentication with NextJS frontend forms

I've created an API hub using Django and a frontend application with NextJS. Currently, I'm working on implementing authentication from the NextJS app to the Django API and I'm seeking advice on best practices. At the moment, the NextJS app ...

What is the best way to pass a variable from a class and function to another component in an Angular application?

One of the components in my project is called flow.component.ts and here is a snippet of the code: var rsi_result: number[]; @Component({ selector: 'flow-home', templateUrl: './flow.component.html', styleUrls: ['./flow.comp ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Unlock the encrypted information in the blockchain

I've been working on encrypting and decrypting values using Node's built-in crypto module. I found a helpful tutorial that showed me how to encrypt the data, but it didn't provide any sample code for decryption. When I tried using code from ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Overcoming Duplicate Messages and Enhancing Performance in Chat Functionality with useOptimistic Method

I'm currently implementing a chat functionality in my Next.js application with Firebase Firestore, and I have encountered two main issues: // UpdatedChatWrapper.tsx const UpdatedChatWrapper = ({ user, allMessages, sendMessageAction }: Props) => { ...