aphex / vite-plugin-ngrok

A Vite plugin for seamless integration with ngrok, allowing you to easily share your local development server with anyone, anywhere.
19 stars 4 forks source link

How to get the ngrok URL? #2

Closed blparker closed 8 months ago

blparker commented 8 months ago

Using this plugin, how can I get the URL from ngrok?

aphex commented 8 months ago

When you run the dev script and vite starts up are you not seeing the ngrok url? It should be lister there with the other vite startup information

blparker commented 8 months ago

Apologies for the poorly worded issue. I do see the URL logged to the console, but I'm trying to get a reference to the URL outside of the plugin (to use the URL downstream).

aphex commented 8 months ago

Interesting. Currently the plugin does not expose the url it just logs it. Can you break down how you would like to use it and what downstream is for you? From what I understand vite plugins do not return custom values.

So maybe you are looking to get a hold of this url from another plugin you're creating? If so we could slap the value into a config object, but I don't think there is any type safe way to do this and allow 3rd party plugins to depend on this plugin's value.

Maybe you are hoping the URL is somehow injected into the runtime code so it is accessible through import.meta.env?

Or maybe you want an event hook to get the value back into your vite.config file?

Also maybe all of this is off, it would be best if you could detail your use case.

blparker commented 8 months ago

The more I thought about, the more I realized that this is probably a niche use case that likely isn't worth supporting. My use case was to be able to add the URL to the list of trusted origins on a Django backend, so I needed to get ahold of the URL in order to dynamically add it to the settings.py file. I managed to get around it by updating what you did:

{
  name: 'start-server-using-ngrok',
  configureServer(server) {

    const { httpServer } = server;

    let listener: Listener;
    httpServer?.on('listening', async () => {
      const address = httpServer.address();
      if (listener || !address || typeof address === 'string') return;

      listener = await _ngrok.forward({
        addr: address.port,
        authtoken: NGROK_AUTH_TOKEN,
        schemes: 'http',
      });

      const url = listener.url();
      server.config.logger.info(`  ➜ ngrok: ${url}`);

      if (url) {
        const filePath = path.resolve(process.cwd(), '../.ngrok_url');
        fs.writeFileSync(filePath, url);
      }
    });

    // Clean up ngrok when the server closes
    httpServer?.on('close', async () => listener?.close());
  }
}

And then, on startup, the backend server reads the URL from this file.

Unless you object, I'm okay to close this issue. Appreciate the help.