인프런 커뮤니티 질문&답변
로그인 버튼 클릭시 500에러 발생
작성
·
1.2K
0
아이디, 비밀번호를 입력하고 로그인 버튼을 누르면 500에러가 발생합니다. 9090 서버 포트는 잘 켜져있다고 뜨고, 코드 올리겠습니다.
<auth.ts>
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import KakaoProvider from "next-auth/providers/kakao";
export const {
  handlers: { GET, POST },
  auth,
  signIn,
} = NextAuth({
  pages: {
    signIn: "/i/flow/login",
    newUser: "i/flow/signup",
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        // credentials 안에 id창에서 입력하는 정보다 담겨있음
        const authResponse = await fetch(`${process.env.AUTH_URL}/api/login`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            id: credentials.username,
            password: credentials.password,
            //next-auth의 credentials에는 username, password로 고정되어 있어서 이를 바꿔줌
          }),
        });
        //로그인 실패시
        if (!authResponse.ok) {
          return null;
        }
        const user = await authResponse.json();
        return user;
      },
    }),
    //kakao로그인을 사용할때
    // KakaoProvider(),
  ],
});
<LoginModal.tsx>
"use client";
import style from "@/app/(beforeLogin)/_component/login.module.css";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { ChangeEventHandler, FormEventHandler, useState } from "react";
export default function LoginModal() {
  const [id, setId] = useState("");
  const [password, setPassword] = useState("");
  const [message, setMessage] = useState("");
  const router = useRouter();
  const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
    e.preventDefault();
    setMessage("");
    try {
      await signIn("credentials", {
        username: id,
        password,
        redirect: false,
      }); //kakao, naver로 바꿀 수 있음
      //client 일때는 next-auth/react의 signIn을 사용
      //server 일때는 @/auth의 signIn을 사용
      router.replace("/home");
    } catch (error) {
      console.log(error);
      setMessage("아이디와 비밀번호가 일치하지 않습니다.");
    }
  };
  const onClickClose = () => {
    router.back();
  };
  const onChangeId: ChangeEventHandler<HTMLInputElement> = (e) => {
    setId(e.target.value);
  };
  const onChangePassword: ChangeEventHandler<HTMLInputElement> = (e) => {
    setPassword(e.target.value);
  };
  return (
    <div className={style.modalBackground}>
      <div className={style.modal}>
        <div className={style.modalHeader}>
          <button className={style.closeButton} onClick={onClickClose}>
            <svg
              width={24}
              viewBox="0 0 24 24"
              aria-hidden="true"
              className="r-18jsvk2 r-4qtqp9 r-yyyyoo r-z80fyv r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-19wmn03"
            >
              <g>
                <path d="M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"></path>
              </g>
            </svg>
          </button>
          <div>로그인하세요.</div>
        </div>
        <form onSubmit={onSubmit}>
          <div className={style.modalBody}>
            <div className={style.inputDiv}>
              <label className={style.inputLabel} htmlFor="id">
                아이디
              </label>
              <input
                id="id"
                className={style.input}
                value={id}
                onChange={onChangeId}
                type="text"
                placeholder=""
              />
            </div>
            <div className={style.inputDiv}>
              <label className={style.inputLabel} htmlFor="password">
                비밀번호
              </label>
              <input
                id="password"
                className={style.input}
                value={password}
                onChange={onChangePassword}
                type="password"
                placeholder=""
              />
            </div>
          </div>
          <div className={style.message}>{message}</div>
          <div className={style.modalFooter}>
            <button className={style.actionButton} disabled={!id && !password}>
              로그인하기
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
<middleware.ts>
export { auth as middleware } from "./auth";
export const config = {
  matcher: ["/compose/tweet", "/home", "/explore", "/messages", "/search"],
};
<route.ts>
export { GET, POST } from "@/auth";
에러 내용 :
TypeError: next_dist_server_web_exports_next_request__WEBPACK_IMPORTED_MODULE_0__ is not a constructor
at reqWithEnvURL (webpack-internal:///(rsc)/./node_modules/next-auth/lib/env.js:15:12)
at httpHandler (webpack-internal:///(rsc)/./node_modules/next-auth/index.js:139:139)
at /Users/imhwarang/projects/zerocho/z-com/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:63815
at /Users/imhwarang/projects/zerocho/z-com/node_modules/next/dist/server/lib/trace/tracer.js:133:36
    at NoopContextManager.with (/Users/imhwarang/projects/zerocho/z-com/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)
너무 길어서 다 올릴수는 없네요 에러내용을
답변 3
2
0

npm i @auth/core@0.27 next-auth@5.0.0-beta.11 msw@2.1
이렇게 설치하고 .env에서 AUTH_URL을 지웁니다. 그리고 auth.ts에서 NEXT_PUBLIC_BASE_URL을 대신 씁니다. .env에 AUTH_URL을 쓰지 않는 게 핵심입니다.
const authResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/login`, {아직 msw@2.2의 버그는 해결하지 못했습니다.
https://github.com/mswjs/msw/issues/1658#issuecomment-1953599080
이런 식으로 버그 제기를 하고는 있으나 언제 고쳐질 지는 모르겠습니다. 해결되는대로 다시 공유드리겠습니다.
0








갑자기 생긴걸로 봐서는 다음 버전 나올 때까지 기다리거나 버전을 한 버전 낮춰서 해결해봐야할 것 같습니다.