In a Next.js API route (server-side code), calling client.createToken(userId) on a client from StreamChat.getInstance(process.env.STREAM_KEY, process.env.STREAM_SECRET) throws Error: tokens can only be created server-side using the API Secret, even though the secret is passed. The key and secret env vars are correctly set, and the reporter confirmed they are read properly. The client instance reports the secret as undefined despite the secret being passed to getInstance.
stream-chat: tokens can only be created server-side using the API Secret (Next.js API route)
StreamChat.getInstance is a singleton: it creates the client only on the first call in the runtime, and later calls with different parameters are ignored. If the client was first initialized anywhere without the secret value, for example in client-side code, the shared instance has no secret set and token creation throws. Fix: construct a new StreamChat client with your key and secret inside your API route instead of getInstance, which always creates a fresh instance with the values you pass. The maintainer confirmed this is the correct approach when you need different instances or key pairs.
Source: https://github.com/GetStream/stream-chat-js/issues/665