2

Having some trouble with setting up nextauth v4. Getting this error:

Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'}.

To fix it they say you have to add the url path to a .env file when deploying. I’m working on localhost so this shouldn't be a problem, but after adding it, still the same error.

When I comment out the async session callback in [...nextauth] file, the error doesn’t pop up and the session is “authenticated” but doesn’t persist. I’ve been staring it at this for a good while now and could use some help!

[...nextauth].js

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  providers: [
    CredentialsProvider({
      async authorize(credentials, res) {

        //find existing user
        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
        });

        if (
          credentials.email === user.email &&
          credentials.password === user.password
        ) {
          return user;
        } else {
          return res.status(409).send({ message: "No user with that email." });
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        return token;
      }
    },
    //commenting this function and no error shows up
    async session({ session, token }) {
      if (token) {
        session.id = token.id;
        return session;
      }
    },
  },
  secret: "mysecret",
  jwt: {
    secret: "mysecret",
    encryption: true,
  },
  session: {
    strategy: "jwt",
    maxAge: 1 * 24 * 60 * 60,
  },
});

auth-form

import { signIn, useSession } from "next-auth/react";

export default function AuthForm() {
  const { data: session } = useSession();

  const handleSubmit = async (userData) => {
    const { error, ok, url } = await signIn("credentials", {
      redirect: false,
      email: userData.email,
      password: userData.password,
      callbackUrl: "/profiel",
    });

    if (ok) {
      router.push(url);
    } else {
      alert(error);
    }
  };

  return (
      <Form onSubmit={handleSubmit}>
        <Field id="email" />
        <Field id="password" />
        <button type="submit">{isRegistered ? "Sign in" : "Register"}</button>
      </Form>
  );
}

_app.js

import { SessionProvider } from "next-auth/react";

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}
2
  • In the session callback, move the return session; line after the if block. Do the same with return token; in the jwt callback Commented Feb 19, 2022 at 15:02
  • 1
    That fixed it! Thanks for taking the time to check it out. If you want to post the answer I will mark it as "solved". Commented Feb 21, 2022 at 9:52

1 Answer 1

3

The session and jwt callbacks need to return a session and jwt object respectively. You need to move the return statements in each function after the if block.

callbacks: {
    async jwt({ token, user }) {
        if (user) {
            token.id = user.id;
        }
        return token;
    },
    async session({ session, token }) {
        if (token) {
            session.id = token.id;
        }
        return session;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.