Next.js Discord

Discord Forum

Constructor run multiple times

Answered
Tiphiid wasp posted this in #help-forum
Open in Discord
Tiphiid waspOP
I have this constructor in my class, which caches db-entries on startup:
    constructor() {
        console.log('Caching auth-states from db...');
        prisma.auth_tokens.findMany({
            select: {
                api_token: true,
                web_token: true,
                web_refresh: true,
                api_refresh: true,
                expires: true,
                username: true,
            }
        }).then((val) => {
            val.forEach(dbState => {
                this.authStates.set(dbState.username, this.dbToAuthState(dbState)!)
            })
            this.cached = true;
            console.log('Finished caching auth-states')
        }).catch(err => console.log('Failed to cache auth-states:', err));
    }


This is how I export it:
export const ASP = new AuthStateProvider();

I have an API route which is used to communicate between the middleware and the backend (edge-runtime issue, I'v already asked about that here 2 weeks ago for context).
Some how, I get Caching auth-states from db... and Finished caching auth-states on every time the api-route is fetched by the middleware (which is on every acces to a protected route since it is used to validate tokens).
I hope someone might have an idea, since it literally wore me out pretty bad, I just can't find the issue.

27 Replies

Tiphiid waspOP
So why exactly?
cause its serverless
this means, on every request a new instance of AuthStateProvider is created
and the old class is wiped from memory
so your ASP const is always a new AuthStateProvider
Tiphiid waspOP
So there is literally no way to store persistant data in an api-route?
yes
no way
not in memory
u can use in-memory dbs like redis or any other db
but looking at your code since its i think only one db call u can handle that on every request, wont impact perfomance
Tiphiid waspOP
Yeah but technically I could cache the whole user datatbase on every request again and again, without any reason to do so. Do you maybe have an idea how I could implement a wokring caching mechanism?
Western paper wasp
There are caching mechanisms built in to nextjs! You can use unstable_cache to store and retrieve the results of function calls
Tiphiid waspOP
Ok thanks
@Western paper wasp There are caching mechanisms built in to nextjs! You can use `unstable_cache` to store and retrieve the results of function calls
Tiphiid waspOP
So when I cache everything in the contructor, it stays in cach? Oh and also can I somehow remove something from the cache?
u cant cache a class as i told u
Answer
Tiphiid waspOP
What tags would I use for this task?
my-app-user is a tag
Tiphiid waspOP
Okay, thanks