Hoping someone can help! I’m building a nextJS website and wanting to incorporate some javascript. I want this javascript to run each time a user navigates to a separate page.
Let’s say I want to log something to the console each time.
I’ve written a script here using React. I believe I have to use useEffect?
import React, { useEffect } from 'react'
const Alerter = () => {
useEffect(() => {
console.log("Page Rendered !!");
}, [])
}
export default Alerter
Then, do I have to import that on each individual page.js, and then also run it? Such as the below
import buttonStyles from '../components/global/button.module.css'
//Scripts
import Alerter from '../scripts/runAlert'
export default function LoginPage() {
return (
<div>
<form>
<button className={buttonStyles.button} formAction={login}>Log in</button>
</form>
<Alerter />
</div>
)
}
Is there a cleaner way?
3
Answers
I ended up doing the following. I created a file called 'clientApplication' with the following code
Then in my layout.js I wrapped this around my {children}
This seems to be working okay. Do you see any concerns with it?
The _app.js file in Next.js acts as the entry point for all pages. You can add your JavaScript logic there to ensure it runs on every page navigation.
Try this in your _app.js
Let’s start with fixing your current component. It needs to return something:
However, rather than adding this to every page, here are better approaches:
Layout Component Approach Since Next.js uses a shared Layout component, you could add your effect there to run on all pages:
Custom App Approach You could create a custom
_app.js
(Pages Router) or modify your root layout (App Router) to handle this:Router Events Approach If you specifically want to track navigation events, you can use Next.js router events:
The Router Events approach is particularly good because:
Which approach would work best depends on exactly what you’re trying to achieve. Are you specifically trying to track navigation events, or do you need to run some other kind of initialization on each page load?