Skip to main content

Developer Bytes

Using ngrok with Laravel to Expose Your Local Development Server

Let’s say you need your local Laravel server to be accessed from another device. This is where the ngrok tool comes in handy; it’s great for testing webhooks, 3rd-party API integrations, and so on. The procedure is straightforward, but there may be some pitfalls along the way, which we’ll discuss.

# Project Setup

For this tutorial I’ll be using laravel 12 with inertia and the vue starter kit.

Install a new Laravel project and choose the Vue starter kit:

laravel new laravel-ngrok

laravel new inertia vue project

And after running composer run dev, we have a regular Laravel web app with simple authentication functionality.

# Installing ngrok

Create an account at ngrok.

Download and install ngrok based on your operating system (in my case it’s linux) here: Setup & Installation.

Expose your local app: ngrok http PORT_NUMBERFor example, if it is listening on port 8000, run:

ngrok http 8000

# Fixing Common Issues

Now you’ll have a url that looks something like this: https://eb5e487d234d.ngrok-free.app.

You should put that url as the APP_URL the .env file.

APP_URL=https://eb5e487d234d.ngrok-free.app

Now we should force HTTPS for the ngrok domain; I’m going to do that using a middleware.

First, let’s make a middleware:

php artisan make:middleware NgrokForceHttpsMiddleware

app/Http/Middleware/NgrokForceHttpsMiddleware.php:

use Illuminate\Support\Facades\URL;

class NgrokForceHttpsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        URL::forceHttps($this->isNgrokRequest($request->getHost()));

        return $next($request);
    }

    private function isNgrokRequest(string $host): bool
    {
        if (str_ends_with($host, '.ngrok-free.app')) {
            return true;
        }

        return false;
    }
}

Finally, add the middleware in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(NgrokForceHttpsMiddleware::class);

    // ...
})

Congrats! Your local development server is now accessible from anywhere on the internet through a secure HTTPS tunnel.

Have feedback or questions about this post? Feel free to reach out at [email protected]