Vite + TypeScript + React, build failure with non-zero exit code 2

PLEASE help us help you by writing a good post!

My Netlify site name: ruminate-frontend
Q. Do I have a DNS issue?
A. No, I do not have a customized domain for this site.

Q. Do I have an issue with build process?
A. Yes, I have an issue with preview deployment not production deployment.
When I understand the cause, I do not understand how to debug the issue because what I have taken to debug did not work.

The following is the information that has been returned from Netlify building process:

12:27:45 AM: Netlify Build                                                 
12:27:45 AM: ────────────────────────────────────────────────────────────────
12:27:45 AM: ​
12:27:45 AM: ❯ Version
12:27:45 AM:   @netlify/build 29.26.3
12:27:45 AM: ​
12:27:45 AM: ❯ Flags
12:27:45 AM:   baseRelDir: true
12:27:45 AM:   buildId: 654f10be676e2a6c37d87ce6
12:27:45 AM:   deployId: 654f10be676e2a6c37d87ce8
12:27:45 AM: ​
12:27:45 AM: ❯ Current directory
12:27:45 AM:   /opt/build/repo
12:27:45 AM: ​
12:27:45 AM: ❯ Config file
12:27:45 AM:   No config file was defined: using default values.
12:27:45 AM: ​
12:27:45 AM: ❯ Context
12:27:45 AM:   deploy-preview
12:27:45 AM: ​
12:27:45 AM: Build command from Netlify app                                
12:27:45 AM: ────────────────────────────────────────────────────────────────
12:27:45 AM: ​
12:27:45 AM: $ npm run build
12:27:45 AM: > experiment2@0.0.0 build
12:27:45 AM: > tsc && vite build
12:27:47 AM: Failed during stage "building site": Build script returned non-zero exit code: 2
12:27:47 AM: src/contexts/AuthContext.tsx(3,3): error TS6133: "browserSessionPersistence" is declared but its value is never read.
12:27:47 AM: src/contexts/AuthContext.tsx(6,3): error TS6133: "setPersistence" is declared but its value is never read.
12:27:47 AM: ​
12:27:47 AM: "build.command" failed                                        
12:27:47 AM: ────────────────────────────────────────────────────────────────
12:27:47 AM: ​
12:27:47 AM:   Error message
12:27:47 AM:   Command failed with exit code 2: npm run build (https://ntl.fyi/exit-code-2)
12:27:47 AM: ​
12:27:47 AM:   Error location
12:27:47 AM:   In Build command from Netlify app:
12:27:47 AM:   npm run build
12:27:47 AM: ​
12:27:47 AM:   Resolved config
12:27:47 AM:   build:
12:27:47 AM:     command: npm run build
12:27:47 AM:     commandOrigin: ui
12:27:47 AM:     environment:
12:27:47 AM:       - REVIEW_ID
12:27:47 AM:     publish: /opt/build/repo/dist
12:27:47 AM:     publishOrigin: ui
12:27:47 AM: Build failed due to a user error: Build script returned non-zero exit code: 2
12:27:47 AM: Failing build: Failed to build site
12:27:47 AM: Finished processing build request in 19.839s

In the meantime, this is what I have in the codebase:

import {
  GoogleAuthProvider,
  createUserWithEmailAndPassword,
  onAuthStateChanged,
  signInWithEmailAndPassword,
  signInWithPopup,
  signOut,
} from 'firebase/auth'
import { createContext, useContext, useEffect, useReducer } from 'react'
import { auth } from '../components/api/firebase/index'
import useStatusMessages from '../hooks/StatusHook'

type TestState = {
  email: string
  password: string
  userInfo: any
}

type TestAction = {
  payload?: any
  type: string
}

type StatusStateType = {
  error: string
  success: string
}

type Cell = {
  AuthState: TestState
  AuthDispatch: React.Dispatch<TestAction>
  auth: any
  // auth
  googleAuth: () => void
  Register: () => void
  LogIn: () => void
  logOut: () => void
  //status
  setSuccess: (message: string) => void
  setError: (message: string) => void
  statusState: StatusStateType
}

const AuthContext = createContext<Cell | null>(null)

export const AuthContextProvider = ({
  children,
}: {
  children: React.ReactNode
}) => {
  //  status handling
  const { statusState, setError, setSuccess } = useStatusMessages({
    error: '',
    success: '',
  })
  const initialState: TestState = {
    email: '',
    password: '',
    userInfo: {},
  }

  const AuthReducer = (state: TestState, action: TestAction) => {
    switch (action.type) {
      case 'SET_EMAIL':
        return { ...state, email: action.payload }
      case 'SET_PASSWORD':
        return { ...state, password: action.payload }
      case 'SET_USER':
        return { ...state, userInfo: action.payload }

      default:
        return state
    }
  }
  const [AuthState, AuthDispatch] = useReducer(AuthReducer, initialState)
  //  after page reload we are getting user information from session and updating the global state of AuthState.userInfo with it
  useEffect(() => {
    onAuthStateChanged(auth, (currentUser) => {
      AuthDispatch({ type: 'SET_USER', payload: currentUser })
    })
  }, [])

  // authentication functionality
  // google auth

  const provider = new GoogleAuthProvider()
  //   this authentication functions would be better to be inside of the each respective component instad of context API

  const googleAuth = async () => {
    try {
      const user = await signInWithPopup(auth, provider)
      AuthDispatch({ type: 'SET_USER', payload: user.user })
      setSuccess('User Has Been Authenticated')
      console.log(user)
    } catch (error) {
      const err: any = error
      console.log(err.code)
      setError(err.code)
    }
  }

  // register
  const Register = async () => {
    const { email, password } = AuthState
    try {
      await createUserWithEmailAndPassword(auth, email, password)
      onAuthStateChanged(auth, (currentUser) => {
        AuthDispatch({ type: 'SET_USER', payload: currentUser })
      })
      setSuccess('User Has Been Created')
    } catch (error) {
      const err: any = error
      console.log(err.code)
      setError(err.code)
    }
  }
  // login
  const LogIn = async () => {
    const { email, password } = AuthState
    try {
      await signInWithEmailAndPassword(auth, email, password)
      onAuthStateChanged(auth, (currentUser) => {
        AuthDispatch({ type: 'SET_USER', payload: currentUser })
        console.log(currentUser)
      })
      setSuccess('User Has Logged In')
    } catch (error) {
      const err: any = error
      console.log(err.code)
      setError(err.code)
    }
  }
  // logout
  const logOut = async () => {
    await signOut(auth)
    AuthDispatch({ type: 'SET_USER', payload: {} })
    window.location.reload()
  }

  return (
    <AuthContext.Provider
      value={{
        AuthState,
        AuthDispatch,
        auth,
        logOut,
        Register,
        LogIn,
        googleAuth,
        statusState,
        setError,
        setSuccess,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export const UseAuthContext = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('Context Not Wrapped Reload Page')
  }

  return context
}

Hence, I do not seem to know what is causing the issue nor how to fix it.

The errors are fairly clear. You’ve declared some variables but you’re not using them anywhere. Deleting those should fix the issue. This isn’t a Netlify problem.

Please go back to the original question and check the codebase that I posted which is located under the error message from Netlify console. I do not think that you are carefully reading at all.

In addition, I LITERALLY mentioned that this is a preview deployment issue.
This is NOT production deployment issue. I have no production deployment issue.
I just want to know why the preview feature that is supposed to be working when the production deployment has been successful is not working.

I kindly ask you to read my question carefully.

I have read your thread, but this is still not a Netlify problem. This is something wrong with your code, and based on the provided information, this is all the debugging that we can do about it.

Try running a production build locally, and you’d most likely run into the same issue.

I do not have a problem with production deployment.
The production is successful. It’s only the preview that’s the problem. preview deployment feature from your company’s site is its own unique feature.

how is this not related to Netlify’s issue?

I cloned your repo, and checked out revision 8904dc4 which seems to point to the deploy you’ve shown. There, I see this code:

image

And when building locally, I get the same error:

npm run build

> experiment2@0.0.0 build
> tsc && vite build

src/contexts/AuthContext.tsx:3:3 - error TS6133: 'browserSessionPersistence' is declared but its value is never read.

3   browserSessionPersistence,
    ~~~~~~~~~~~~~~~~~~~~~~~~~

src/contexts/AuthContext.tsx:6:3 - error TS6133: 'setPersistence' is declared but its value is never read.

6   setPersistence,
    ~~~~~~~~~~~~~~


Found 2 errors in the same file, starting at: src/contexts/AuthContext.tsx:3

Like I have been saying, this is a code problem, not a Netlify problem.

For your reference, this is where the error is coming from: Front back merg by johnjang94 · Pull Request #11 · johnjang94/project_ruminate (github.com)

First of all, thank you for trying to look into the problem.
I appreciate you sparing your time to have better response for my inquiry.
On the other hand, it is unfortunate that I am only feeling like you want to make this issue as a debate and that you are in an attempt to win the argument. I want to make sure that this is how I feel besides your true intention.

Now, let’s go back to the topic.
Based on your comment, I learnt that you can also clone my repo.
This gives me another hint because I am having the impression that you can of course look into the history of deployment from my account.

Instead of trying to find an evidence that proves your point by scratching the surface, I would have asked more questions to dig deeper if I were you because I do believe that this case could look strange from the perspective of a 3rd person. I would assume that any other developer might think that either I am an idiot or that this case is weird to bring up in the first place.

Let me confirm you one thing.
Yes, I did have those values that were declared but not used. It is not only you who can read the errors.
In addition, it is very clear what the errors are about just like how you said it. I am just genuinely speechless by the fact that you even paid more effort to dig into clone my repo but not the fact that you tried to check the deployment history and trying learn further about what was going on.

Now, I am here to tell you a long story (including some TMIs) and show you why I keep say that Netlify might have a problem and why this is reasonable suspicion.

I have about three different deployments from one same Github repository.
Each deployment has been made from different branches due to different “testing” purposes.
I have “ruminate-frontend”, “ruminate-test”, and “ruminate-temporary”. On my Github repository, I have branches like the following picture (this is part of what I have):
Github Repo tree

I am making most of the changes on “ruminate-frontend” and the issue came from “ruminate-frontend”.
I have been linking ruminate-frontend from your platform to either front-end branch or front-back-merg branch from my Github repo. I did not want to frequently change the source, but I had about three attempts to change between front-end branch and front-back-merg branch to find out where the problem was arising besides checking my codes.

When I first deployed my original codes on ruminate-frontend which was connected to front-end branch at that time, both the production deployment and the preview feature (which is supposed to be working once the production deployment is successful) were working fine. At that time, the preview looked like this (and this is what I had intended to see):

After I have seen that my first deployment attempt has been successful, I went on to CI/CD my changes and continued to build my application. Then in the middle of the progress, I started to face a new problem (which is the error that we have been discussing about).

Yes, the error has occurred at first due because I had the values that were declared in “import” but not that I was using them. In order to debug this issue, I have taken 2 different actions:

option 1: I have commented out the codes.
option 2: I have deleted those specific codes.

Here are the results:
option 1: the production deployment was successful when I re-deployed on Netlify with the latest commit option.

option 2: the same result came back like option 1 for the production deployment.

Now, in this case, because the production deployments were successful for both cases…
I was expecting that the preview would also be functional. On the other hand, the preview was continuously failing. I have repeated the same process for 5 hours to find out what is happening.
During this 5 hours, I have also changed the source for the production deployment from front-end branch to front-end-merg branch to see if the same error might occur. I did face the same issue, so I went back to the front-end branch.

This is when the weird thing happened.
I came to realize that there was another way to see what the UI looks like after the production deployment was successful. Take a look at the following picture for your reference:

From here, I was able to check that the production was working as I have intended:

You can see the change in the navbar compared to the first picture I showed you earlier.
However, the preview mode in the deployment was not catching up with the changes:

From the above picture, you can see how the deploy preview keeps failing to launch from front-back-merg branch when the production is actually being made either on front-end-test branch or front-end branch. This looked weird to me because this action was done after I pushed the same code that both front-end branch and front-end-test branch have. I realized that my corrected code works on front-end branch and front-end-test branch, so I pushed the same code to front-back-merg branch. According to this logic, both the production and the preview mode should work.

This is where I am bringing my issue to the surface.
Because the preview mode is not working properly on Netlify (from my own perspective), I have decided to turn off the preview mode. Now, this is what I see on ruminate-frontend when I decide to deploy from both front-end branch and front-end-test branch:

Yes, Netlify does seem to have an issue with preview mode.
My assumption is that if the production is being made on front-end branch, then the preview mode should also be made from the production branch (which is the front-end branch). If the production is being made on front-end-test branch, so should the preview mode be.

I don’t understand how the preview mode is building up the code from front-back-merg branch with an old codebase data when there are changes being made. How is it possible that the preview mode shows the status using different codebase from another branch when the production has the latest codebase from another branch?

There is nothing wrong with my code because I have successfully done the debug after the clear error in my codes.

Do you still say that it is my code problem, not Netlify?
Can you honestly look into the issue and what is happening with the preview mode?

I do not bring up the issue that is so obvious.
When I brought up the issue, I did so because I learnt that the issue was not something I could fix.
I am not an idiot who does not know how to read the error message.

I’m sorry if you feel this is an argument, but the only way for me to show this is not a Netlify issue was by bringing in more evidence in front of you that indicated this being a code problem. I haven’t called you an idiot, or didn’t assume you cannot read an error message. But, a lot of times, users don’t see the error message (or find it hard to find among other logs), so usually we need to point to the error message and they figure it out themselves. After considering and reviewing all the information you gave, this is what I can add:

Your code that’s failing, is currently building from the HEAD of PR 11:

HEAD would indicate the current latest commit made to PR 11

Checking PR 11: Front back merg by johnjang94 · Pull Request #11 · johnjang94/project_ruminate (github.com), the last commit seems to be:

If you check the repo’s files at that particular commit: project_ruminate/src/contexts/AuthContext.tsx at 8904dc44d1618a816e9d354cf9cea17298c518c4 · johnjang94/project_ruminate (github.com), you can see the code that you have an issue with, still exists in there.

Now, you’ve removed the problem code from your front-back-merg branch: project_ruminate/src/contexts/AuthContext.tsx at front-back-merg · johnjang94/project_ruminate (github.com), but it still exists in that particular PR (PR 11).

What you probably need to do is, now that you’ve merged PR 1, you need to create another PR from your front-back-merg branch to your front-back branch that should include the latest changes.

Beyond this, I don’t have anything to add to this thread and I apologise if I offended you, but I still don’t agree with your assertion of this being a Netlify issue.