sentry-javascript icon indicating copy to clipboard operation
sentry-javascript copied to clipboard

NextJS SSR with Vercel not working

Open camillevingere opened this issue 1 year ago • 30 comments

Is there an existing issue for this?

  • [X] I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues
  • [X] I have reviewed the documentation https://docs.sentry.io/
  • [X] I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/nextjs

SDK Version

8.9.2

Framework Version

14.2.4

Link to Sentry event

No response

SDK Setup

// This file configures the initialization of Sentry on the server. // The config you add here will be used whenever the server handles a request. // https://docs.sentry.io/platforms/javascript/guides/nextjs/

import * as Sentry from "@sentry/nextjs";

const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;

Sentry.init({ dsn: SENTRY_DSN || 'DSN',

// Adjust this value in production, or use tracesSampler for greater control tracesSampleRate: 1,

// Setting this option to true will print useful information to the console while you're setting up Sentry. debug: false,

integrations: [Sentry.prismaIntegration()],

// Uncomment the line below to enable Spotlight (https://spotlightjs.com) // spotlight: process.env.NODE_ENV === 'development',

});

Steps to Reproduce

  1. Take a NextJS project
  2. Deploy in production on Vercel
  3. Don't forget to put env variables

Expected Result

The errors should be logged in Sentry

Actual Result

The errors are logged in local development in CSR and SSR but in production on VERCEL only the CSR is working. All that is an server side error is not logged in Sentry.

camillevingere avatar Jun 24 '24 14:06 camillevingere

Hi, can you share how you are throwing errors that are not logged? Thanks!

lforst avatar Jun 24 '24 14:06 lforst

Hi, here is an example :

`export const requiredAuth = async () => { const user = await auth();

if (!user) { throw new AuthError("You must be authenticated to access this resource."); }

return user; };`

This is working in local but not on Vercel.

camillevingere avatar Jun 25 '24 05:06 camillevingere

Where are you calling requiredAuth? In a server component? Api route? Route handler? App dir, pages dir?

lforst avatar Jun 25 '24 09:06 lforst

I am using it in a Server Component

camillevingere avatar Jun 26 '24 06:06 camillevingere

Would you mind giving a small but complete example? Please verify that this is not your issue: https://docs.sentry.io/platforms/javascript/guides/nextjs/#:~:text=Errors%20in%20Nested%20React%20Server%20Components (section "Errors in Nested React Server Components")

lforst avatar Jun 26 '24 11:06 lforst

Sure,

I already checked and this is not the case. Reminder : it is working in local.

Here is a SSR page :

import {
  Layout,
  LayoutContent,
  LayoutHeader,
  LayoutTitle
} from "@/components/layout/layout";
import { buttonVariants } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import { requiredAuth } from "@/lib/auth/helper";
import Link from "next/link";
import AnalysisChart from "./AnalysisChart";
import { columns } from "./columns";
import { getMarkets } from "./market.query";
import { getProducts } from "../../courses/product.query";
import { Typography } from "@/components/ui/typography";

export default async function MarketAnalysisPage({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const user = await requiredAuth();
  const page = Number(searchParams.page ?? 0);

  const products = await getProducts({
    userId: user.id,
  });

  if (
    products.products.find(
      (product) => product.name === "Devenir Développeur Freelance V2",
    ) === undefined
  ) {
    return (
      <Layout>
        <LayoutHeader>
          <LayoutTitle>Analyse du marché</LayoutTitle>
        </LayoutHeader>
        <LayoutContent>
          <Typography className="mb-4">
            Tu dois avoir la formation{" "}
            <strong>Devenir Développeur Freelance™️</strong> pour accéder à cet
            outil.
          </Typography>
          <Link
            className={buttonVariants({ size: "sm", variant: "outline" })}
            href="/formations/devenir-developpeur-freelance"
          >
            Acheter la formation
          </Link>
        </LayoutContent>
      </Layout>
    );
  }

  const markets = await getMarkets({
    userId: user.id,
    userPage: page,
  });

  return (
    <Layout>
      <LayoutHeader>
        <LayoutTitle>Analyse du marché</LayoutTitle>
      </LayoutHeader>
      <LayoutContent className="flex flex-col gap-8">
        {markets && <AnalysisChart data={markets} />}
        <div>
          <Link
            className={buttonVariants({ size: "sm", variant: "outline" })}
            href="/analysis/market/new"
          >
            Nouvelle entrée
          </Link>
        </div>
        {markets && (
          <DataTable
            columns={columns}
            data={markets.sort(function (a, b) {
              return b.date.getTime() - a.date.getTime();
            })}
          />
        )}
      </LayoutContent>
    </Layout>
  );
}

With the requiredAuth which throw an error if not connected. Sentry logs in local but not in production using Vercel.

camillevingere avatar Jun 27 '24 12:06 camillevingere

Yeah okay, that error should definitely be reported.

I tried to reproduce with a server component like yours:

export const dynamic = 'force-dynamic';

export default async function Page() {
  throw new Error('boom');
  return <p>hi</p>;
}

and it is reported, even when deploying on vercel. Can you verify that you set your DSN correctly and maybe turn on debug: true in your server Sentry.init() call? Thanks.

lforst avatar Jun 27 '24 12:06 lforst

Capture d’écran du 2024-07-01 10-33-19 Capture d’écran du 2024-07-01 10-32-38 Capture d’écran du 2024-07-01 10-31-36

I checked again, I have the DSN in env variables, the same in NEXT_PUBLIC_SENTRY_DSN and SENTRY_DSN (since it is working client side, I think the DSN is good).

As you can see the error is logged in Vercel, and the client is logging the error in the console which is a Server Component.

I checked the build logs with debug true, nothing unusual (but I can send you all the logs if you want)

camillevingere avatar Jul 01 '24 08:07 camillevingere

If you add

  beforeSend(event, hint) {
    console.log(event.exception?.values);
    return event;
  },

Do you see anything in the logs?

lforst avatar Jul 01 '24 08:07 lforst

I tried and nothing, since it is not send I doubt it goes in the beforeSend :/

camillevingere avatar Jul 01 '24 09:07 camillevingere

I tried to put the DSN in hardcode to be sure, still nothing logged

camillevingere avatar Jul 01 '24 11:07 camillevingere

Update: server actions errors seemed to be logged in sentry (but not the other server errors)

camillevingere avatar Jul 01 '24 11:07 camillevingere

I have the same issue and even as @camillevingere tried to hardcoded DSN into the code, but nothing is sent if an exception is related to a RSC.

I see the doc stating that Since Next.js is not exposing errors thrown in nested React Server Components, the SDK can currently not capture them., and potentially it is the reason. https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#report-react-component-render-errors

However, I remember it was okay before. or is it my memory problem???

alvis avatar Jul 01 '24 12:07 alvis

For the context, I'm using the latest version of the SDK 8.13

alvis avatar Jul 01 '24 12:07 alvis

Honestly, I am also lost. If anybody could share reproduction I can take a closer look.

lforst avatar Jul 01 '24 13:07 lforst

I have the same issue and even as @camillevingere tried to hardcoded DSN into the code, but nothing is sent if an exception is related to a RSC.

I see the doc stating that Since Next.js is not exposing errors thrown in nested React Server Components, the SDK can currently not capture them., and potentially it is the reason. https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#report-react-component-render-errors

However, I remember it was okay before. or is it my memory problem???

I also saw this but it is working for me in LOCAL !!! It is a total non sense... Does it work for you in local environement ?

camillevingere avatar Jul 01 '24 15:07 camillevingere

UPDATE : it is working in local but with pnpm run dev and not pnpm run start after a build

So it was working because it was not SSR in dev

I have this in my global-error.tsx

useEffect(() => { Sentry.captureException(error); }, [error]);

Do I have to put in in error.tsx as well in my app folder ?

camillevingere avatar Jul 01 '24 16:07 camillevingere

@camillevingere if you have an error.tsx down the line, it will swallow the error, yes. It's the same as adding an error boundary or a try-catch somewhere.

lforst avatar Jul 02 '24 07:07 lforst

But please try to put together a reproduction example I can take a look at. error.tsx is only responsible for the client-side, not server.

lforst avatar Jul 02 '24 07:07 lforst

Can I invite you on my project ? (on github)

camillevingere avatar Jul 03 '24 10:07 camillevingere

@camillevingere sure thing!

lforst avatar Jul 03 '24 12:07 lforst

@lforst Did you have the time to look ? :)

camillevingere avatar Jul 04 '24 09:07 camillevingere

@camillevingere yes, nothing in particular stood out to me. I don't know how to properly deploy your app which I would need to do in order to reproduce the issue. Is it just vercel deploy?

lforst avatar Jul 04 '24 13:07 lforst

image

(PS: don't forget to remove the project from Vercel when you are done please)

camillevingere avatar Jul 04 '24 15:07 camillevingere

@lforst Any news ?

camillevingere avatar Jul 05 '24 14:07 camillevingere

@camillevingere This is on our radar. This issue is not p0 for us as of now. We will get to it at some point.

lforst avatar Jul 08 '24 08:07 lforst

I can't reproduce this bug with your app because it doesn't build due to env vars not being set. Please provide a minimal reproduction example so we can take a look. Thanks!

lforst avatar Jul 08 '24 10:07 lforst

Ensure your instrumentation.ts file is at the same level as your app directory.

Was having similar issue where not working in deployment but working locally.

Issue for me was:

nextjs project dir was setup like

/ROOT/app /ROOT/src /ROOT/public

sentry wizard added instrumentation.ts to /src (i imagine since usally src contains the app folder)

moving the instrumentation.ts file out into /ROOT/instrumentation.ts (so its colocated with app folder) fixed it.

maybe for sentry folks but might be useful to flag in docs where it must be located since docs say "To set up this file, add a instrumentation.ts file to the root directory of your Next.js application (or inside the src folder if you're using one)" (so not clear if it needs to be colocated)

jel-massih avatar Jul 24 '24 22:07 jel-massih

The wizard currently covers the usual case of having either a src folder or an app folder as Vercel describes moving the app folder inside the src directory (here).

Thanks for sharing your example. We will investigate to also cover other use-cases (like having the app folder next to the src directory).

@camillevingere did moving the instrumentation file work for you?

s1gr1d avatar Jul 25 '24 08:07 s1gr1d

This issue has gone three weeks without activity. In another week, I will close it.

But! If you comment or otherwise update it, I will reset the clock, and if you remove the label Waiting for: Community, I will leave it alone ... forever!


"A weed is but an unloved flower." ― Ella Wheeler Wilcox 🥀

getsantry[bot] avatar Aug 24 '24 07:08 getsantry[bot]