1

I have the following utility function that is just a singleton class for storing a counter.

export class CounterSingleton {
  private static instance: CounterSingleton;
  private count: number;

  private constructor() {
    this.count = 0;
  }

  public static getInstance(): CounterSingleton {
    if (!CounterSingleton.instance) {
      CounterSingleton.instance = new CounterSingleton();
    }
    return CounterSingleton.instance;
  }

  public increment(): void {
    this.count++;
  }

  public getCount(): number {
    return this.count;
  }
}

I want the counter class instance to be accessible within api routes. I have no problem with this.

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { CounterSingleton } from "@/utility/counter";
import type { NextApiRequest, NextApiResponse } from "next";

type Data = {
  counter: number;
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const counter = CounterSingleton.getInstance();
  counter.increment();
  res.status(200).json({ counter: counter.getCount() });
}

First api call: { counter: 1 }

Second api call: { counter: 2 }

When i access the same counter class within the middleware. It always gives me counter as 0.

import { NextResponse } from "next/server";
import { CounterSingleton } from "./utility/counter";

export function middleware() {
  const counter = CounterSingleton.getInstance();
  console.log(counter.getCount());
  return NextResponse.next();
}

Can someone explain to me why is the singleton instance different in middleware?

1
  • 1
    any solution , i tried to do it as global without luck Commented Jun 21, 2023 at 12:43

1 Answer 1

0

Middleware might be executed before the API routes. That means API has not yet incremented the instance of CounterSingleton class; Middleware has access singleton instance before it's been incremented. That's why it's returning 0.

Sign up to request clarification or add additional context in comments.

3 Comments

Bump! Facing the same with route handlers
Are you still having that problem?
Our team decided to accept that multiple instances can exist when running Next.js in dev mode. To handle this, we’re using Redis to centralise the state of what was supposed to be a singleton class. For example, if this class spawns a worker, we also store the worker’s PID in Redis so that other instances of the same class in different processes can check whether a worker is already running. It’s a bit of a hacky solution, but it works for now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.