Next.js Discord

Discord Forum

Shared State not working Across Modules in Next.js App Router

Unanswered
Singapura posted this in #help-forum
Open in Discord
SingapuraOP
I’m building a Next.js application where I need a logger to be configured in one part of the app (instrumentation.ts) and used in others. Here’s a simplified version of what I’m doing:

logger.ts
let logger = { a: 'hello' }; export const configureLogger = (opt: object) => { Object.assign(logger, opt); // Modify the logger object in place }; export { logger, configureLogger };

instrumentation.ts
import { configureLogger, logger } from 'services/test'; export const register = async () => { if (process.env.NEXT_RUNTIME === 'nodejs') { console.log('Before configure:', logger); // { a: 'hello' } configureLogger({ b: 'world' }); console.log('After configure:', logger); // // { a: 'hello', b: 'world' } } };

page.tsx
import { logger } from 'services/test'; const Page = async ({ params: { site, locale, pagePath = '' }, }: { params: RouteParams; }) => { console.log('Logger in B:', logger); // // { a: 'hello' } instead of { a: 'hello', b: 'world' } return ( <div>Hello</div> ); }; export default Page;

Problem:
When I configure the logger in Module A, it correctly updates the logger instance. However, when I try to access the logger in Module B, it doesn’t reflect the updated configuration—it still shows the initial state ({ a: 'hello' }).

What I've Tried
Proxy Pattern: I tried using a Proxy to always reference the latest logger instance. This didn’t work as expected, with Module B still showing stale data.

Global State with globalThis: I also attempted to store the logger in a global object using globalThis, it worked, but I'm looking for a solution without global variables

Getter and Setter, didn't worked.

Questions
Is there something specific to how Next.js handles modules that could cause this behavior?
Are there any best practices in Next.js for sharing and updating state like this across modules?
Could SSR or module caching be affecting how the state is shared?

Thanks in advance for reading me and help!

0 Replies