#Run initialisation code before any onGet handlers fire

10 messages · Page 1 of 1 (latest)

fathom dove
#

I'm writing a library and I need users to be able to run some setup code. From my tests it seems that any code added to the root or entry files execute only when Qwik starts streaming a response, which happens after the onGet handler is fired.

Is there any way to run some initialisation code on the server before any onGet functions are called?
It wouldnt be great DX for users to have to write their own code to check if an initialisation step has been taken inside every onGet.

Thanks and appreciate any pointers!

timid wing
#

Have you tried useServerMount?

fathom dove
#

onGet unfortunately run first

timid wing
#

Ah, can you provide a code example? That might help to understand your goal.

fathom dove
#

@timid wing

import library from 'my-custom-library';

// This needs to run before any onGet methods are called
library.initialize(...)

export const onGet = () => {
  // Using the library is not possible without first running an initializer
  library.run()
}

Of course this is possible inside every onGet (or variations of it), but that isn't a great DX:

if (!isInitialized) {
  isInitialized = true
  library.initialize(...)
}
timid wing
#

Hmm, what about putting it in entry.*.tsx?

fathom dove
#

Ye I tried that but it only runs after the onGet

hoary grotto
fathom dove
#

@hoary grotto Yeah i thought about that, but then the user would have to call it, or pass it in with every request.
I think i might try create a Vite plugin that can inject the code but it will require a bit of experimentation

hoary grotto
#

Ah I see you are writing the library yourself, cool! Yeah then I understand you would like to solve it some other way ✌🏼