Sentry.io
Sentry.io is a cloud-based error monitoring service that helps developers capture and log errors (including stack traces and request information) in real-time (when they occur in production). They support a wide range of languages and frameworks through their "sentry-*" opensource SDKs that are hosted on GitHub (the error logging SDKs for javascript, React, Capacitor, Next.js, and many more have an MIT license, but not all sentry packages do, for example, the self-hosted version of sentry uses a license called FSL that is NOT an OSI-approved license).
Beyond error tracking, Sentry also offers performance monitoring features as well as a feature called Sessions Replays, which lets you capture and then replay the user interactions that happened before the error occurs, making it easier to reproduce an error and more.
Know that Sentry has open source SDKs but the SaaS service is a paid service. Sentry.io has a (free) Developer plan for developers who want to start a side project or just experiment with the service. The plan includes logs for up to 5000 errors, 10,000 performance metrics, and more. To learn more about the quotas for the free plan or check out the pricing of other plans, I recommend checking out their pricing page.
Create an account (sign up)
- Go to sentry.io and then click on Get Started
- Next, they ask you to create an account. You can do so using your email address, or you can connect via your account from a git provider. I chose GitHub (but feel free to click on Google or Azure DevOps if you already have such an account). I'm surprised they don't offer you to connect using GitLab or Bitbucket 😲) as I intended to connect my GitHub account at some point anyway, as there are some features like converting an error log into a ticket that I want to try out (I usually try not to connect too many accounts which each other as a breach into one of them could potentially give the attacker access to the services that are linked to it too, but in this case, I chose to because in the next step, we need to connect our GitHub account anyway and allow Sentry.io to create tickets on GitHub for me)
- for a guide about creating a GitHub account, check out my chapter Create a GitHub account (sign up) in the GitHub post
- next, a pop-up window will open, asking you to authorize Sentry.io; there is one request they do, which is called Act on your behalf, this means that Sentry.io will be able to do tasks on your repositories, this is needed so that Sentry.io can, for example, help open / update issues in your repositories
- click on Authorize Sentry.io, and you will get redirected to Sentry.io
- on the next page, they ask us if we already have a Sentry.io account; if you do follow their instructions in the message, however, if, like me, you don't have an account yet, click on New Account
- next, enter a user name for Sentry.io (you can either use your full name, or as I did, use your GitHub username, or use any display name you like, if already or later plan to work in a team, then I recommend you chose a name they will recognize)
- then you need to choose an organization name, and the placeholder of the field says company name; however, even if the name is required, it does NOT mean you can NOT sign up as an individual; organizations in Sentry.io are like organizations on GitHub, they don't solely represent companies but it can be any group you want, as I have no organization on GitHub either I just MY_USER_NAME-projects as name
If your content is located in the EU (or for reasons related to GDPR), you may want to chose to store your Sentry data in the EU, so when asked about your preferred Data Storage Location make sure you chose European Union (EU); This is very important because once selected, your data storage location can't be changed
- then check the mandatory terms checkbox
- for the email updates, choose whatever you prefer
- finally click on Continue / Create your Account
Next, we have finally arrived on their welcome page. You can either click on Start (which I recommend you do, but more on that in the next chapter) to get a guided tour on how to set up the sentry or your team, or you can click on the link below to skip the onboarding.
Create a Sentry.io project
If you just finished the previous chapter and clicked on Start, then you will have come to a page where you get asked to choose your main framework, else go to your Sentry.io account and on the left, click on Projects and then Create project
Choose whatever framework you like (during onboarding, you can only add one at a time. However, you will later be able to add more if you want. For example, add sentry for a PHP Backend API, sentry for React for your frontend code, and sentry for iOS and Android for your apps, if that's, is your technology stack)
Next, I chose an alert frequency. I kept the default value Alert me on every new issue (you can change this later)
Then you can Name your project and assign a team to it. I again kept the default values.
Finally, click on Create Project
Now click on Configure SDK
Sentry.io SDK for Next.js installation
You can use the Sentry Wizard or follow their manual setup toturial. I chose to use the Wizard as it guides you through setting up Sentry. I will also install some test files to ensure everything is working. If you chose manual, you may want to copy the DSN they give you at the end of the page (a Sentry DSN is an API key you will use when setting up your SDK)
Before using the wizard, I recommend committing your latest changes (if you haven't already) and doing a last sync before launching the sentry wizard, this way you will be able to see what stuff Sentry.io will add to your project, and you will see what got changed in existing files like the next.config.mjs file
In your VSCode terminal (or your preferred command line tool), type the following command:
Or, if you prefer to use the wizard without sending telemetry data to sentry.io (usage statics and crash reports), then add the --disable-telemetry
option to the command, like so:
First, you will get asked if you accept installing the sentry wizard npm package. Press y
to accept and press Enter
to move on
After the installation, the wizard will automatically get launched, and it will start asking you questions about your setup preferences:
Are you using Sentry SaaS or self-hosted Sentry? You probably want to choose Sentry SaaS (sentry.io) like I did (but if you are a company and need a custom solution, then you might want to look at the hosted version), then press Enter
.
Do you already have an account? chose Yes (if you did follow the previous chapter or already had an account before), then press Enter
(or choose No if you have no account yet and follow the account creation process)
Then, the sentry wizard will ask you to log in, which will open the sentry login page in your default browser. Log into your account, then go back to your terminal.
Select your Sentry project, choose your Sentry Project from the list (when using the wizard, Sentry will have automatically created a project for the SDK you chose earlier for you; if, however, you don't see a Project listed here, you can check out the Create a Sentry.io project chapter to create a project first)
Now, Sentry will install the latest Sentry SDK for Next.js.
Do you want to route Sentry requests in the browser through your NextJS server to avoid ad blockers? Sentry wants to know if it should route its requests through your Next.js server. By doing so, Sentry attempts to bypass the block lists of adblocker addons that are installed in some browsers. This means Sentry will first send the client-side requests to a URL on your server, and then your server will forward the request to the Sentry API. I personally chose Yes as I want to increase the chance of getting bug reports but feel free to answer No (if for example, you don't want to have the extra traffic, on your server backend, that this redirect will cause)
Do you want to enable React component annotations to make breadcrumbs and session replays more readable? Next Sentry is asking if we want to use the feature called React component annotations which attempts to use component names in reports instead of more cryptic selectors, I think this is a nice feature, so I selected Yes, if you already use Sentry.io and don't want to change how bug reports work, then leave it on No, you can always turn it on/off via the configuration later if you want
I turned React component annotations on and then noticed that my react-three-fiber animation had stopped working, this is because React component annotations adds data attrobites to components which React Three Fiber does not like, and which then creates bugs which print the following in your console:
TypeError: Cannot read properties of undefined (reading 'sentry')
So if you plan on using React Three Fiber then you should answer to this question with NO, to learn more about this problem and how to disable React component annotations manually in the configuration have a look at my warning box in the Sentry.io for Next.js configuration chapter
Do you want to create an example page chose YES (we will later use it to test the Sentry setup, and then we will delete it)
Are you using a CI/CD tool to build and deploy your application? chose YES (if you are using Vercel, GitHub actions, or any other CI/CD deployment tool); If you do NOT use one, choose NO)
The Sentry.io Wizard will give you a SENTRY_AUTH_TOKEN string if you choose yes. If you use a CI/CD for your deployments, copy the token, and save it in a secure location, you will need this token later if, for example, you set up a custom GitHub action. You will want to add that token environment variable to your GitHub secrets. If you use another CI/CD service, check out their documentation to learn how to use that token to upload source maps to Sentry automatically. If using Vercel, you can use the Sentry integration for Vercel, which will set the Vercel environment variables for you, or if you prefer you can add the token manually to your environment variables using the Vercel environment variables interface.
CI/CD tools can authenticate themselves to Sentry.io using the SENTRY_AUTH_TOKEN environment variable and then use the Sentry.io API to automatically upload the source maps of your build to Sentry.io. Later, if there is a bug report on Sentry.io, it will be able to use the source maps instead of the minified build files to show you where the error occurred.
Did you configure CI as shown above? chose YES
That was the last question:
Successfully installed the Sentry Next.js SDK!
After answering all questions, the Sentry SDK will edit your next.config.mjs to add the withSentryConfig Sentry configuration, and it will have added several sentry.*.config files (to the root of your project) that contain environment-specific configurations, it will also create some other files depending on what answers you gave, like a page.tsx that we can now use to test the setup
If you use Vercel for your deployments, then you don't need to set the SENTRY_AUTH_TOKEN yourself; you can use the Sentry integration for Vercel, which will set the Vercel environment variables for you, I recommend you do that now, as all you need to do is click on the Add integration button, and then continue with the tutorial
Sentry.io Next.js example page
Next, as suggested by the wizard at the end of the installation process, it is recommended to start the development server using the npm run dev
command, and then we visit the Sentry example page in our browser at http://localhost:3000/sentry-example-page
On that page, hit the Throw Error! button and then click on the link just below to visit your Sentry projects issues page
Now wait for the backend and frontend errors to appear (this can take a few minutes, which is a good time to refresh your cup of coffee ☕ (or whatever beverage you prefer))
As soon as the two errors appear, feel free to click on them and have a look at what error logging on Sentry.io looks like
Before we commit/sync all the changes Sentry.io did in our project, delete the app\sentry-example-page\
folder, including the page.jsx
example page, and then also delete the app\api\sentry-example-api\
folder including the route.js
API example route file that Sentry.io created to test the error logging, you will not need them anymore.
Sentry.io for Next.js configuration
Sentry.io can be customized a lot and has several places to change the default configuration.
Sentry wizard has edited our next.config.mjs
, and it should now look like this:
By default, the options that the wizard set for us are good enough. As soon as you have the time, I recommend checking out the Extend your Next.js Configuration Sentry.io documentation, which explains what each option does
To enable reactComponentAnnotation is usually a good idea as it makes reports more readable by using component names instead of long selectors, but to make this feature happen Sentry needs to add a data attributes to components, this does usually not pose a problem except for react-three-fiber which does not like those extra attributes at all, which means that React component annotations are great unless you use React Three Fiber
For now if you use React three fiber the only workaround is to turn the Sentry React component annotations option off, by setting the reactComponentAnnotation
variable to false
It is only after I had opened an Issue #13413 in the sentry-javascript repository that I found the Issue #530 in the sentry-javascript-bundler-plugins repository, which has a comment by one of the Sentry SDK mainteners, they mentioned that they consider adding more options in the future to let you exclude components, however as of now those options are not available yet, so for now we can NOT enable React component annotations and exclude React three fiber, we MUST completly disable the feature
Another file that got added to the root of our project is sentry.client.config.ts
, which is used to configure Sentry.io for client components. Check out the Next.js SDK Configuration Options documentation for more details about each option. I slightly modified my configuration file to be like this:
Lines 3-12: I added two variables for the replaysOnErrorSampleRate and the tracesSampleRate, replaysOnErrorSampleRate I set to zero by default to not produce replays when not in production, then line 6-8 I added a check to verify if the current environment is production and if it is I tell Sentry to always make a replay if there is an error (be careful with this option, in the free plan you only have 50 replays per month, which is why I only turn it on in production, also in development it is usually the developer themself that triggers the error so there is not really a need for a replay); the tracesSampleRate I set it to 0.1, meaning 10% of the traces will get sent to Sentry but then line 10-12 I disable them in development (this is to ensure no performance metrics are getting calculated when the app is running on a local computer, to check local performance it is preferred to use the developer tools), you may want a lower or higher value depending on what plan you are on and then check if you reach your limits or not and then adjust over time
Line 27: I completely disabled replaysSessionSampleRate, meaning there will be no replays being made when there is no error; the free plan has 50 replays per month, and I prefer to keep all the replays for cases where there is a bug
Line 38: I pass the environment to Sentry, meaning Sentry will know if the environment is preview or production (that value is based on the Vercel environment on which Next.js got deployed)
If you copy paste the sentry.client.config.ts
above into your project make sure you update the YOUR_SENTRY_DSN_URL placeholder with your own Sentry DSN
sentry.edge.config.ts
are the options for when Next.js uses the Vercel Edge Network. I kept that file, but feel free to adjust any values to fit your use case.
sentry.server.config.ts
is again similar to the previous two, just this one is specifically for Next.js server-side options. I also kept this file as is
There is, however, one option in the server configuration that is commented out (by default) that you might want to consider. The option lets you use the Spotlight js package by Sentry. If you're going to use it, I recommend checking out the documentation to install and setup Spotlight in a Next.js project
Allowed domains filter
By default Sentry.io will accept reports from whatever domain they originate as long as the DSN is yours, you can however explicitly whitelist domains that are allowed to send in reports, in which case Sentry will check the Origin and Referer headers and exclude reports from domains that you did not whitelist
To specific domains instead of all, use the following steps:
- open your Sentry.io account
- in the navigation on the left click on Settings
- on the settings page there is now another navigation on the left, there click on Projects
- now, on the projects page, click on the name of your project
- you are now in the general settings of your project, scroll down a bit until you see the Client Security section
- in that section there is an option called Allowed Domains
- in that field enter all the domains you will use for your project
The field for allowed domains is a textarea, meaning you don't add a comma seperated list but instead you add one domain per row, let's assume you want to whitelist your example.com
domain as well as two subdomains foo.example.com
and bar.excample.com
, then this would be what your whitelist looks like:
If you deploy on Vercel you might want to add a wildcard for the *.vercel.app
domain, which is the domain that vercel uses for branch (preview) deployments
If after adding domains to the list, it will take a few minutes before the filter gets updated, so wait a little bit before testing your Sentry.io requests
If there is a problem with your allowed domains, then you might start seeing 403 errors (Failed to load resource: the server responded with a status of 403) for requests to sentry.io (or your tunnel URL)
To make sure the allowed domains are not the problem just replace the list with a single asterisk (*
) to allow all requests from any domain and check if the error goes away, if that's the case then you know at least what the "real" problem is
Disable / Enable "reports from localhost" (filter)
If you want to disable (or re-enable) the Sentry.io reports from the localhost filter, do this:
- visit Sentry.io and log in
- in the left navigation on the bottom, click on Settings
- then, in the Settings navigation on the left, click on Projects
- click on the project name
- then in navigation on the left, under PROCESSING, click on Inbound Filters
- on that page, there is an option called Filter out events coming from localhost. Either disable or enable that option. When enabled Sentry will filter reports coming from localhost and when disabled it will NOT
Sentry v7 to v8 migration
If you had Sentry v7 already installed in your project and now want to upgrade to Sentry v8, I recommend you use the Sentry migration codemod which will automatize the upgrading process and hence simplify the migration process a lot
Investigation failed request / missing reports
If you have a feeling that something is wrong, you either get 403 responses from Sentry (or your tunnel URL), or you trigger an error but it won't show up, I recommend starting with the following steps:
- if you are using the sentry domain whitelist feature, meaning you don't just have an asterisk (
*
) set as default value, then you might want to have a look at the Allowed domains filter chapter and make sure the domain making the request is on the whitelist, maybe you are using a regex and the submain you are on is not covered by the regex - If you are on localhost, then maybe localhost request are blocked, in this case have a look at the Disable the "reports from localhost" filter chapter, and make sure that localhost is set to enabled
- Have a look at your inbound filters, mayby one of those is excluding the Issues
- Make sure the DSN you are using is correct, make sure the DSN (Sentry client key) that your project is using is correct, eventually it is wrong key from another project, or someone has disabled or even deleted a key that is still in use
- Have a look at the following chapter Using the Sentry.io API to debug issues which will show you how to make quick requests to the Sentry.io API to help you narrow down the cause of the missing Issues
Using the Sentry.io API to debug issues
When trying to log my CSP reports in Sentry.io, I could see that some reports got dropped, but the stats page did not give me the exact reason.
To find the exact reason why a request was dropped, you can use the Sentry.io API.
To get some data about the events, you can use Curl to make the following request:
You will, however, need an auth token, which you can get to create a custom integration for your organization, like so:
- to get an auth token, go to "Settings", then in the section "Developer Settings," click on "Custom Integrations"
- then click on "Create New Integration", choose "Create Internal Integration", and click on "Next"
- then add a project name, and then under "Permissions" for "Issue & Event", choose "Read" then click on "Save Changes"
- then, on the Integration page, scroll down and click on "New Token", copy the token (you will need it later to make API requests), and then click on "Done"
- finally, click on save changes
Now that you have your auth token, you can make an API call like this (replace MY_ORGANIZATION with the name of your organization on Sentry.io and replace xxx111 at the end with your actual auth token):
On Mac / Linux, use the terminal or your favorite command line tool to execute the command. On Windows, I recommend using Git Bash
This will hopefully help you understand if your requests got filtered, were invalid, or if there was another reason why they got dropped.