[SOLVED] Help! VERCEL - ERROR NEXTJS Authentication on prod. Error: 401 Unauthorized

Hello,

I try to go live with the “Authenticate Users with MetaMask” example on Vercel with NextJS.

The local project works fine but I cannot make it works on Vercel… I got an error 401 Unauthorized.

Here is the configuration:

{
  "name": "test-auth",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@moralisweb3/next": "2.9.0",
    "@next/font": "13.1.2",
    "ethers": "^5.6.9",
    "moralis": "^2.9.0",
    "eslint": "8.32.0",
    "eslint-config-next": "13.1.2",
    "next": "13.1.2",
    "next-auth": "^4.10.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "wagmi": "0.6.1"
  },
  "devDependencies": {
    "@types/react": "18.0.25",
    "typescript": "4.9.3"
  }
}

[…moralis].ts :

import { MoralisNextApi } from '@moralisweb3/next';

export default MoralisNextApi({
  apiKey: process.env.MORALIS_API_KEY || '',
  authentication: {
    domain: 'amazing.dapp',
    uri: `https://${process.env.NEXT_PUBLIC_VERCEL_URL}` || '',
    timeout: 120,
  },
});

I write some logs on signin page:

import { MetaMaskConnector } from 'wagmi/connectors/metaMask';
import { signIn } from 'next-auth/react';
import { useAccount, useConnect, useSignMessage, useDisconnect } from 'wagmi';
import { useRouter } from 'next/router';
import { useAuthRequestChallengeEvm } from '@moralisweb3/next';

function SignIn() {
    const { connectAsync } = useConnect();
    const { disconnectAsync } = useDisconnect();
    const { isConnected } = useAccount();
    const { signMessageAsync } = useSignMessage();
    const { requestChallengeAsync } = useAuthRequestChallengeEvm();
    const { push } = useRouter();

    const handleAuth = async () => {
        if (isConnected) {
            await disconnectAsync();
        }

        const { account, chain } = await connectAsync({ connector: new MetaMaskConnector() });
        console.log("account: ", account);
        console.log("chain: ", chain);
        
        const { message } = await requestChallengeAsync({ address: account, chainId: chain.id });
        console.log("message: ", message);
        
        const signature = await signMessageAsync({ message });
        console.log("signature: ", signature);
        
        // redirect user after success authentication to '/user' page
        const { url } = await signIn('moralis-auth', { message, signature, redirect: false });
        console.log("url: ", url);
        /**
         * instead of using signIn(..., redirect: "/user")
         * we get the url from callback and push it to the router to avoid page refreshing
         */
        push(url);
    };

    return (
        <div>
            <h3>Web3 Authentication</h3>
            <button onClick={handleAuth}>Authenticate via Metamask</button>
        </div>
    );
}

export default SignIn;

Here the logs and error:

Hi @Kroustof90, Can you check the vercel server logs to check if there are more details on what caused the error.

Hi, here is the logs when I call the function

Errors are empty

There are Error 304 on “[GET] /api/auth/providers” and on “[GET] /api/auth/csrf”, then Error 401 on “[POST] /api/auth/callback/moralis-auth”

Were you able test the production build on localhost environment without any errors?

If yes, then can you share your production url? I will try to test it on my end.

I tried build on localhost environment. I have no error while building. But I have the same error locally. On localhost dev it works fine.

Here is the url to try : https://test-auth-g5h5f2n00-kroustof.vercel.app/signin

I see this error in console when i click on the login button. It did not open metamask

If you test this Moralis repo (https://github.com/MoralisWeb3/demo-apps/tree/main/nextjs_moralis_auth.) in production, do you have any issue to make it works ?

My repo is basically a copy paste of the authentication tutorial with NEXT JS, so I don’t know what to do…

It prompts normally when I click on login… I will try again

try this link: test-auth-flax.vercel.app

I deployed something long back. But not sure if your code is similar to mine.
https://moralisauth.vercel.app/signin

New Url gave me this error in console. Is it the same error which you are seeing?

Yours works fine. But Moralis has recently updated their API and packge ‘@moralisweb3/next’ with a new tutorial… It seems the problem may come from that

Yes, this is the same error

hmm, let me try deploying the latest version and I will get back to you.

If you have time, may I ask you to try to deploy the tutorial repo and see if it works to know if I am doing something wrong on my part

1 Like

Here is the latest build. I copied the code directly from tutorial repo and updated the app. It seems to run without any error. You can also check my repo to compare your code.
Demo: https://moralisauth.vercel.app/user
GitHub: https://github.com/JohnVersus/demo-apps-nextjs_moralis_auth

Since your app is running without any error on localhost it could also be something related to the env variables added on the vercel. So maybe double-check if the variables related to the next-auth are added correctly.

1 Like

I will clone your repo and try it. Obviously I am doing something wrong. I let you know if I get it right this time.

Thanks

1 Like

By the way, did you use yarn or npm to install the packages ?