Next.js Discord

Discord Forum

Middleware triggering on all pages when it shouldn't

Answered
Chilean jack mackerel posted this in #help-forum
Open in Discord
Chilean jack mackerelOP
I have a middleware function that is suppose to post a tracking event when the home page / is viewed.

export default async function middlware(req: NextRequest) {
  // if user is on the homepage, count as visitor
  if (req.nextUrl.pathname === "/") {
    try {
      await analytics
        .track("pageview", {
          page: "/",
          country: req.geo?.country,
        })
        .then(() => {
          console.log("Successful track.");
        })
        .catch((err) => {
          console.error(err);
        });
    } catch (err) {
      // fail silently during attempt
      console.error(err);
    }
  }
  return NextResponse.next();
}

// determine what paths middleware runs on
export const config = {
  matcher: "/",
};


The problem is, when I view my page /analytics, it is still doing a GET request to my / page and then posting an event to my analytics tracker.
I am using a server component for the analytics page.

I do not want to have a / page tracked everytime i view /analytics. Everytime i referesh my analytics page it is showing a new page view when only home page views are being tracked in the middleware. Any help?

You can see it for yourself by refreshing https://parisosuch.com/analytics
Answered by Rafael Almeida
maybe you have a next/link in the /analytics page that is prefetching the home page? so it triggers the middleware and does the view count
View full answer

20 Replies

Answer
I personally would not do tracking on the middleware because it will slow down the entire page load, you could do it on the page component itself after the page has been mounted
@Rafael Almeida maybe you have a `next/link` in the `/analytics` page that is prefetching the home page? so it triggers the middleware and does the view count
Chilean jack mackerelOP
oh my goodness you are right, i am using Link to go back to the home page. i didn't know it prefetches it
also thanks for the advice! i had a feeling it would slow down the render and since im only tracking the home page i could just do it on that page
would it still slow it down if im doing an asyncronous middleware component>
yeah notice that you are awaiting the analytics.track function before returning NextResponse.next(), so for every request to the home page it will wait until the pageview has been completed
you want the middleware to run as fast as possible so the rest of the page can start loading
but doing it in the middleware will completely avoid ad block extensions so I think it could be a trade-off 🤔
Chilean jack mackerelOP
ah i see, I did not have it awaiting before and then it just wouldn't work in a vercel deployment until I added that await, so might as well do it on the homepage
good to know thank you!
i am doing this just to track my portofolio visits
and more importantly, what projects they click
yeah without the await it won't work because the middleware will stop running very fast after sending the page, doing it in the client is better for performance
@Rafael Almeida yeah without the `await` it won't work because the middleware will stop running very fast after sending the page, doing it in the client is better for performance
Chilean jack mackerelOP
I see, I currently have my home page as a server component but I should turn it into a client component and do my API call there async without an await so it will call in the background
I thought server components are rendered faster and statically? Would this make my home page slower if it was client side?
you can create a separate client component just for analytics tracking, then import it in your server component page
Chilean jack mackerelOP
Genuis
thank you so much
i learned more about nextjs in this forum post from you than else where
np! :blobthumbsup: