Disable HTTP request methods in your demo environments

DALL-E: 16th century drawing of a gate barrier guarding a desktop PC on a hill

Here's a quick tip for your public demo environments. Let's say that you want to disable "unsafe" HTTP request methods, like POST and DELETE, to prevent users from messing up your demo instance data.

You can use middleware class that will check for method type and generate appropriate response. Here's how to do that in Laravel.

<?php

declare(strict_types=1);

namespace Kami\Cocktail\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;

class FilterMethodMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $allowedRoutes = [
            'auth.login',
            'auth.logout'
        ];

        if (App::environment('demo') && !$request->isMethodSafe() && !$request->routeIs($allowedRoutes)) {
            return response()->json([
                'message' => 'This action is currently disabled!'
            ], 405);
        }

        return $next($request);
    }
}

As you can see, condition check is pretty simple. We first check in what environment we are. Then we use a helpful method from Symfony request class called isMethodSafe(), which checks if the request is any of the following methods:

  • GET

  • HEAD

  • OPTIONS

  • TRACE

And the last thing is a route check since we can have some routes that we want to allow unsafe method, in this case login and logout routes.

Inside the condition we just return a json response with a custom message and status code.

Find me on