Access server state in server actions/components
Unanswered
Miniature Pinscher posted this in #help-forum
Miniature PinscherOP
I have set up my Next.js 15 app with a custom server. What this server does on startup is that it populates a Map with a few items. If I run a
server.ts
page.tsx
setInterval() and console log the Map's size every second, I can see it's correct size. However, when I try to import this Map inside a server component/action, it is always empty. Thus, it seems as if I can't access my custom servers state in my components. The reason I need to do this is because I'm trying to abandon my API server which manages several active websockets, and instead of communicating with my old API server via fetches, I wanted to move the logic into my Next.js app instead (with a custom server NOT deployed on Vercel of course). Can anyone knowledgable here point me in the right direction?server.ts
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { store, populateStore } from "./server/store";
const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
// Populates the store, which is a Map(), with a few items.
populateStore()
setInterval(() => {
// Correctly prints the size of the Map
console.log(store.size);
}, 10000);
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
handle(req, res, parsedUrl);
}).listen(port);
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? "development" : process.env.NODE_ENV
}`,
);
});page.tsx
import { store } from "@/server/store";
export default async function Page() {
// This route is compiled (dev mode) and loaded long after store is popululated. But still logs as empty (Map {})
console.log(store);
return (
<div>
</div>
);
}4 Replies
Miniature PinscherOP
For the record, I also attempted to populate my store in instrumentation.ts (without a "custom server" but instead the standalone output), and it resulted in the exact same, can't access the Map in my server components.
Wirehaired Vizsla
A new map will be instantiated each time you insert that map.
The best and quickest workaround would be to save the data in redis and get it from there.
The best and quickest workaround would be to save the data in redis and get it from there.
@Wirehaired Vizsla A new map will be instantiated each time you insert that map.
The best and quickest workaround would be to save the data in redis and get it from there.
Miniature PinscherOP
What if what I store in the map is actually a complex object, in this case a websocket connection?
Why can I not have server sided state when I’m not running it on the edge anyway?