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
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
2
Answers
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.If your Next.js application with NextAuth authentication is redirecting to
localhost
after a successful login when deployed on AWS EC2, that should mean theNEXTAUTH_URL
environment variable is not set correctly in the production environment.You should confirm that the
NEXTAUTH_URL
environment variable is set to your AWS EC2 instance’s public DNS or IP address, and not tolocalhost
.The
.env
file should look like this:Make sure this
.env
file is included in your Docker container (and is not referenced in the.dockerignore
!).In your
signIn
action andauthOptions
, the callback URL should be correctly set using theNEXTAUTH_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 withNEXTAUTH_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.