inflearn logo
강의

Course

Instructor

Next + Create a SNS service with React Query

Logging in with next-auth

next auth error

393

hollis9797

16 asked

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

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

 

react next.js react-query next-auth msw

Answer 3

1

hollis9797

해결했습니다.

loginForm 에서

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

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

0

communityai8509

안녕하세요, 인프런 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

zerocho

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

캡처링부분 질문있습니다.

0

73

2

깃에 소스코드를 찾을 수 없습니다.

0

112

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

97

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

109

2

css 라이브러리 추천 부탁드립니다

0

140

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

130

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

118

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

169

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

184

3

폴링이 필요없는 이유

0

93

2

next Request Memoization과 react cache

0

108

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

83

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

173

2

프레임워크 여론 파악법

0

124

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

101

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

102

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

65

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

131

2

next.js 에서 로그인에 관하여

0

138

1

Next의 route handler에 대한 질문이 있습니다.

0

101

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

97

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

84

2

vanilla-extract 못찾는 문제

0

227

2

fetch 캐싱과 revalidate 관련

0

84

2