The login API endpoint is running on a separate docker container at http://localhost:8080/api/account/login. I have a UI in NextJs, when running it locally (npm run dev) everything runs fine. However when built and ran as a docker container, the login api does not seem to be reachable.
This is the error log when trying to sign in:
Error: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11372:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.authorize (/app/.next/server/pages/api/auth/[...nextauth].js:263:33)
at async Object.callback (/app/node_modules/next-auth/core/routes/callback.js:362:14)
at async AuthHandler (/app/node_modules/next-auth/core/index.js:302:28)
at async NextAuthApiHandler (/app/node_modules/next-auth/next/index.js:22:19)
at async NextAuth._args$ (/app/node_modules/next-auth/next/index.js:107:14) {
cause: Error: connect ECONNREFUSED 127.0.0.1:8080
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8080
}
}
This is my [...nextauth].js file
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { LOGIN_API } from "../../../utils/CommonUtils";
export default NextAuth({
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const res = await fetch(LOGIN_API, {
method: 'POST',
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" }
})
const user = await res.json()
// If no error and we have user data, return it
if (res.ok && user) {
return { name: user.username, image: user.photoUrl }
}
// Return null if user data could not be retrieved
return null
}
catch (error) {
console.error('Error:', error);
return null;
}
}
})
],
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: '/login',
}
})
How can I resolve this problem?
I found that when I ran the docker container in network host mode (--network host) in Linux, everything works fine. However, Windows can't use this network mode option. So I am looking for a better solution.
I have also tried this, using a common network in a docker compose file: Docker alternative to --network host on macOS and Windows but this did not work. The login api is still unreachable.
I am not very proficient with Docker, so please let me know if I'm missing something important. Thank you!
I found a solution that works, renaming the api url to http://api-name instead of http://localhost:8080 allows the login api to be called. The api-name is the name given to the api service in the docker compose file.
This seems to be an issue only in the nextauth.js file. As I tried putting the login api call outside of the nextauth.js file and it was reachable and worked fine.
If anyone has an explanation of what's going on, please do share. Thanks.