skip to Main Content

Im deploying my Nextjs 14 app in AWS EC2 using AWS CLI, Docker, Github.
For authentication i use next-auth. Every time user get access sucessfully Next auth redirects it to localhost.

.env

enter image description here

Dockerfile:

FROM node:21 as builder
WORKDIR /app
COPY package*.json ./

RUN npm install –force

COPY . .

RUN npm run build

EXPOSE 80

CMD ["npm","run", "start"]

signIn action:

signIn('credentials', {
      email: values.email,
      password: values.password,
      callbackUrl: `${process.env.NEXTAUTH_URL}`
    })

auth.ts:

import NextAuth, { NextAuthConfig } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'

export const authOptions: NextAuthConfig = {
  providers: [
    CredentialsProvider({
      async authorize(credentials, req) {
        if (!credentials.email || !credentials.password) return null
        const { email, password } = credentials
        console.log(credentials, 'credentials')
        try {
          const response = await fetch(
            'http://**********:6060/auth/signin',
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({ email, password })
            }
          )
          const data = await response.json()
          return data
        } catch (err) {
          console.log(err)
          return null
        }
      }
    })
  ],
  session: {
    strategy: 'jwt'
  },
  trustHost: true,
  secret: process.env.AUTH_SECRET,
  callbacks: {
    jwt({ token, user }) {
      if (user) {
        return { ...token, ...user }
      }
      return token
    },
    session: ({ token, session }) => {
      session.user = token.user
      session.token = token.token
      return session
    },
    authorized({ auth }: { auth: any }) {
      return !!auth?.user // this ensures there is a logged in user for -every- request
    }
  },
  pages: {
    signIn: '/sign-in' // overrides the next-auth default signin page https://authjs.dev/guides/basics/pages
  }
}

export const {
  handlers: { GET, POST },
  auth
} = NextAuth(authOptions)

The NEXTAUTH_URL variable is available in the container logs but not in the browser. Please refer to the container logs for more information

enter image description here

enter image description here
Thanks for helping!

2

Answers


  1. If you want to have an environment variable available in the browser from a nextjs backend you must prefix with NEXT_PUBLIC_. See Bundling Environment Variables for the Browser.

    Login or Signup to reply.
  2. If your Next.js application with NextAuth authentication is redirecting to localhost after a successful login when deployed on AWS EC2, that should mean the NEXTAUTH_URL environment variable is not set correctly in the production environment.

    Client Browser
            |
            v
    AWS EC2 Instance (Docker Container)
            |
            v
    Next.js App (with NEXTAUTH_URL configured)
    

    You should confirm that the NEXTAUTH_URL environment variable is set to your AWS EC2 instance’s public DNS or IP address, and not to localhost.
    The .env file should look like this:

    NEXTAUTH_URL=http://<Your_EC2_Public_DNS_or_IP>
    

    Make sure this .env file is included in your Docker container (and is not referenced in the .dockerignore!).

    FROM node:21 as builder
    WORKDIR /app
    COPY package*.json ./
    COPY .env ./
    
    RUN npm install --force
    
    COPY . .
    
    RUN npm run build
    
    EXPOSE 80
    
    CMD ["npm","run", "start"]
    

    In your signIn action and authOptions, the callback URL should be correctly set using the NEXTAUTH_URL (which you have)

    Note: if you want to expose an environment variable to the browser in a Next.js application, you should prefix it with NEXT_PUBLIC_. However, this is not the case with NEXTAUTH_URL.
    The NEXTAUTH_URL environment variable is used by NextAuth.js on the server-side to configure the base URL for the NextAuth.js API routes. It is not meant to be exposed to the client-side or browser, as it is used for backend operations such as sending verification requests, callbacks, and so on.

    Next-auth should not require environment variables to be available for the browser to redirect. It uses the NEXTAUTH_URL on the server-side to determine where to redirect after a successful authentication. This means it should be set to the actual URL where your Next.js application is hosted, so that NextAuth.js can create the correct redirect URLs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search