error =TypeError: "ikm"" must be an instance of Uint8Array or a string
Asked Answered
M

7

8

I use next.js typescript,next-auth,prisma,mangodb and I got this error:
TypeError: "ikm"" must be an instance of Uint8Array or a string in vscode
And I got these 2 errors in console:
Error 1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Error 2 SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

this is my [...nextauth]:

import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
import GoogleProvider from 'next-auth/providers/google';
import Credentials from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { compare } from 'bcrypt';
import prismadb from '../../../lib/prismadb';

export default NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID || '',
      clientSecret: process.env.GITHUB_SECRET || '',
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID || '',
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
    }),
    Credentials({
      id: 'credentials',
      name: 'Credentials',
      credentials: {
        email: {
          label: 'Email',
          type: 'text',
        },
        password: {
          label: 'Password',
          type: 'passord',
        },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error('Email and password required');
        }

        const user = await prismadb.user.findUnique({
          where: {
            email: credentials.email,
          },
        });

        if (!user || !user.hashedPassword) {
          throw new Error('Email does not exist');
        }

        const isCorrectPassword = await compare(
          credentials.password,
          user.hashedPassword
        );

        if (!isCorrectPassword) {
          throw new Error('Incorrect password');
        }

        return user;
      },
    }),
  ],
  pages: {
    signIn: '/auth',
  },
  debug: process.env.NODE_ENV === 'development',
  adapter: PrismaAdapter(prismadb),
  session: { strategy: 'jwt' },
  jwt: {
    secret: process.env.NEXTAUTH_JWT_SECRET,
  },
  secret: process.env.NEXTAUTH_SECRET,
});

and this one is my prismadb:

import { PrismaClient } from '@prisma/client';

const client = global.prismadb || new PrismaClient();
if (process.env.NODE_ENV === 'production') global.prismadb = client;
export default client;

and this one is global.d.ts:

import { PrismaClient } from '@prisma/client';
import type { MongoClient } from 'mongodb';
declare global {
  namespace globalThis {
    var prismadb: PrismaClient | undefined;
  }
}

The thing is when I try to register I got error but account I create in database.

Moon answered 15/3, 2023 at 19:25 Comment(0)
C
3

I had same exact error, i was able to register but not login.

Reason is typo!

Correct configuration

NEXTAUTH_JWT_SECRET="xxxxx"

NEXTAUTH_SECRET="yyyyy"

Wrong configuration

NEXAUTH_JWT_SECRET="xxxxx"

NEXTAUTH_SECRET="yyyyy"

T was missing => Before : NEXAUTH_JWT_SECRET After : NEXTAUTH_JWT_SECRET

Contradance answered 11/12, 2023 at 12:43 Comment(0)
A
3

mine was fixed by just adding NEXTAUTH_SECRET="" in your .env , even in the version 5 this is happening so that is the solution for this .

Agonistic answered 26/2 at 11:43 Comment(0)
E
1

I have been fighting the same error for the last few hours. I just got past it in my code. In the [...nextauth].js options, I had jwt{secret: process.env.JWT_SECRET} defined. I removed it completely and that resolved the error. I am now able to log in. You may also need to make sure your NEXTAUTH_SECRET is set correctly. Run openssl rand -base64 32 in the terminal and generate the secret. Then in [...nextauth].js, add the option secret: "your output from openssl rand -base64 32" or process.env.NEXTAUTH_SECRET. I hope this helps .

Looking back at your code, it looks like you need to define the secret in the options. Here is what my [...nextauth].js looks like. I am only using the Credentials provider.

export default NextAuth({
  site: process.env.NEXTAUTH_URL,
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "Email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        
        try {
          const res = await fetch("http://localhost:3000/api/auth/validate-credentials", {
            method: "POST",
            body: JSON.stringify(credentials),
            headers: { "Content-Type": "application/json" },
          });

          if (!res.ok) {
            throw new Error("Invalid credentials");
          }

          const user = await res.json();
          
          if(user){
            return user;
          } else{
            return null;
          }
        } catch (error) {
          console.error("Error in authorize:", error);
          return null;
        }
      },
    }),
  ],
  secret: "Yo/0duPLAErkzTcBlgWGWR4eaVyivqU6a+M/ot0fo9c=",
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 days
    updateAge: 24 * 60 * 60, // 24 hours
    generateSessionToken: () => {
      return randomUUID() ?? randomBytes(32).toString("hex");
    },
  },
  pages: {
    signIn: '/login',
  },
  callbacks: {
    async redirect({ url, baseUrl }) {
      // Allows relative callback URLs
      if (url.startsWith("/")) return `${baseUrl}${url}`
      // Allows callback URLs on the same origin
      else if (new URL(url).origin === baseUrl) return url
      return baseUrl
    }
  },
});
Eigenvalue answered 25/3, 2023 at 4:12 Comment(0)
C
0

Please make sure that you have NEXTAUTH_JWT_SECRET and NEXTAUTH_SECRET

as env variables, for any case.

Additionally strategy: "database", (instead of strategy: "jwt") is the advice in docs for v4.

Chinkapin answered 6/4, 2023 at 23:54 Comment(0)
K
0

Please make sure that your env variable of NEXTAUTH_JWT_SECRET is same which you use in ...[nextauth] jwt-secret.

...[nextauth]/route.ts file

    session: {
        strategy: "jwt",
    },
    jwt: {
        secret: process.env.JWT_SECRET,
    },

.env file

JWT_SECRET="NEXT-JWT-SECRET"
Karyotin answered 11/11, 2023 at 20:14 Comment(0)
P
0

Check your .env.local file. Usualy problem in here

Pull answered 21/3 at 14:54 Comment(0)
T
0

This answer is for nextjs14 and nextauth v5: I had the same issue with signing in to GitHub as the provider, I was able to fix it by adding the AUTH_SECRET variable inside the .env file, I am using next auth version 5, so I use AUTH_SECRET, not NEXTAUTH_SECRET.

Tremor answered 25/3 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.