Introduction to ngrok
ngrok is a powerful tool that enables developers to expose their local servers to the internet either for testing or sharing purposes.
Getting Started with ngrok API
Installation
# Install ngrok using npm
npm install -g ngrok
Creating HTTP Tunnels
import ngrok from 'ngrok';
(async function() {
const url = await ngrok.connect(3000);
console.log('Tunnel URL:', url);
})();
Authenticating Your Account
await ngrok.authtoken('YOUR_AUTH_TOKEN'); // Replace with your ngrok auth token
Inspecting Traffic
ngrok provides a web interface to inspect and replay the requests:
console.log('Inspect URL:', ngrok.getApiUrl());
Advanced Tunneling Options
const tunnel = await ngrok.connect({
addr: 3000,
proto: 'http',
auth: 'user:password',
subdomain: 'mysubdomain',
region: 'us'
});
console.log('Advanced Tunnel URL:', tunnel);
Managing Tunnels
// Stopping a tunnel
await ngrok.disconnect(url);
// Listing active tunnels
const tunnels = await ngrok.active();
console.log('Active Tunnels:', tunnels);
Example: Building a Node.js App with ngrok
Let’s create a simple Node.js application that uses ngrok to expose a local web server.
const express = require('express');
const ngrok = require('ngrok');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(port, async () => {
const url = await ngrok.connect(port);
console.log(`App listening at http://localhost:${port}`);
console.log(`Tunnel URL: ${url}`);
});
With this setup, you can access your local server from any device using the generated ngrok URL.
ngrok simplifies the development workflow by providing a secure and easily accessible URL for local servers, making it essential for modern web development.
Hash: 84b6f03ebe1a75941beef705415e235b0dbd9fd23eb2939f4738bbe8839f78ea