인프런 커뮤니티 질문&답변

hollis9797님의 프로필 이미지

작성한 질문수

Next + React Query로 SNS 서비스 만들기

next-auth로 로그인하기

next auth error

24.10.03 14:53 작성

·

39

0

스크린샷 2024-10-03 오후 2.50.17.png
// auth.ts

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
} = NextAuth({
  pages: {
    signIn: "/i/flow/login",
    newUser: "/i/flow/signup",
  },
  providers: [
    CredentialsProvider({
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        const authResponse = await fetch(
          `${process.env.NEXT_PUBLIC_BASE_URL}/api/login`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              id: credentials.username,
              password: credentials.password,
            }),
          }
        );

        if (!authResponse.ok) {
          return null;
        }

        const user = await authResponse.json();
        return {
          email: user.id,
          name: user.nickname,
          image: user.image,
          ...user,
        };
      },
    }),
  ],
});

 

// route.ts

export { GET, POST } from "@/auth";

각종 커뮤니티 글을 보긴했지만,, 해당 에러는 보이지 않아서 문의 남깁니다.

 

서버쪽 에러는

[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror

[auth][cause]: 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 (webpack-internal:///(rsc)/./src/auth.ts:31:38)

at async Module.callback (webpack-internal:///(rsc)/./node_modules/@auth/core/lib/actions/callback/index.js:241:39)

at async AuthInternal (webpack-internal:///(rsc)/./node_modules/@auth/core/lib/index.js:66:24)

at async Auth (webpack-internal:///(rsc)/./node_modules/@auth/core/index.js:127:34)

at async /Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:55759

at async eO.execute (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:46527)

at async eO.handle (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:57093)

at async doRender (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:1345:42)

at async cacheEntry.responseCache.get.routeKind (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:1555:40)

at async DevServer.renderToResponseWithComponentsImpl (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:1475:28)

at async DevServer.renderPageComponent (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:1901:24)

at async DevServer.renderToResponseImpl (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:1939:32)

at async DevServer.pipeImpl (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:914:25)

at async NextNodeServer.handleCatchallRenderRequest (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/next-server.js:272:17)

at async DevServer.handleRequestImpl (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/base-server.js:810:17)

at async /Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/dev/next-dev-server.js:339:20

at async Span.traceAsyncFn (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/trace/trace.js:154:20)

at async DevServer.handleRequest (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/dev/next-dev-server.js:336:24)

at async invokeRender (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/lib/router-server.js:173:21)

at async handleRequest (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/lib/router-server.js:350:24)

at async requestHandlerImpl (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/lib/router-server.js:374:13)

at async Server.requestListener (/Users/kimyoungwoong/Desktop/next-x/node_modules/next/dist/server/lib/start-server.js:141:13)

[auth][details]: {

"code": "ECONNREFUSED",

"provider": "credentials"

}

이렇게 발생하고 있습니다.

신 버전인 만큼
.env
AUTH_SECRET=woong
작성 해놨고
.env local 같은 경우는

NEXT_PUBLIC_API_MOCKING=enabled

NEXT_PUBLIC_BASE_URL=http://localhost:9090

작성해놨습니다. 잘 해결이 안되서 글 남깁니다.

 

답변 3

1

hollis9797님의 프로필 이미지
hollis9797
질문자

2024. 10. 03. 14:59

해결했습니다.

loginForm 에서

 await signIn("credentials", {
        username: id,
        password,
        redirect: false,
      });

해당 부분에서 redirect 옵션을 기입하지 않아서 생긴 문제로 발생했습니다. 기본값이 true이지 않았나 생각이 듭니다.
해당 글은 남겨두겠습니다 혹시나 저같은 사람이 있지않을까 싶어서..

0

인프런 AI 인턴님의 프로필 이미지

2024. 10. 03. 14:56

안녕하세요, 인프런 AI 인턴입니다.

hollis9797님의 질문 내용을 보니, next-auth 인증 과정에서 fetch 요청이 실패하여 서버 측에서 ECONNREFUSED 에러가 발생하고 있습니다. 이는 주로 네트워크 연결 문제로 인해 발생하며, 인증 서버에 접근할 수 없을 때 발생할 수 있습니다. 여러 가지 원인을 고려할 수 있는데, 몇 가지 확인하고 조정할 수 있는 사항을 말씀드리겠습니다.

  1. 서버 주소 확인: .env.local 파일에 NEXT_PUBLIC_BASE_URLhttp://localhost:9090로 설정되어 있습니다. 해당 주소로 실제 서버가 실행되고 있는지, 그리고 올바르게 작동 중인지 확인해 주세요. 해당 포트에서 API 서버가 제대로 작동 중인지 먼저 체크하는 것이 중요합니다.

  2. Mock Server 실행 여부:

    • msw를 사용하고 있다고 하니, 서버가 정상적으로 실행되고 있는지 확인해 보세요. 예를 들어 npm run mock과 같은 명령어로 실제로 서버가 시작되는지 확인할 수 있습니다.
  3. 환경 변수 경로 확인:

    • .env 파일이 프로젝트 루트(즉, package.json 파일과 같은 디렉토리)에 있는지 확인해 보세요. 환경 변수 파일이 올바른 위치에 있어야 합니다.
  4. 다른 인증 제공자 테스트:

    • 문제 없이 동작하는 다른 인증 제공자가 있는지 테스트해 보세요. 이는 문제가 특정 인증 제공자에 국한되어 있는지를 판단하는 데 도움이 될 수 있습니다.
  5. 유사한 기존 답변 확인:

위의 참고 링크들은 비슷한 문제를 겪었던 학생들의 질문과 강사님의 답변을 포함하고 있어 도움이 될 수 있습니다.

저는 질문자님의 이해를 돕고자 지식 공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식 공유자께서 답변해 주실 것입니다.

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

2024. 10. 03. 14:55

백엔드 서버가 안 켜진 것으로 보입니다. localhost:9090에 켜져 있어야 하고, console.log`${process.env.NEXT_PUBLIC_BASE_URL}/api/login`) 도 해보셔서 주소 정상적으로 나오는지도 확인해보세요.