Usage | laravel-honeypot-go | Spatie       

 SPATIE  

laravel-honeypot-go
===================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-honeypot-go](https://spatie.be/docs/laravel-honeypot-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-honeypot-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-honeypot-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/laravel-honeypot-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-honeypot-go/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-honeypot-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-honeypot-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-honeypot-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-honeypot-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Usage in Inertia ](#content-usage-in-inertia)
2. [ Usage in Livewire ](#content-usage-in-livewire)
3. [ Disabling in testing ](#content-disabling-in-testing)
4. [ Customizing the response ](#content-customizing-the-response)
5. [ Customizing the spam protection ](#content-customizing-the-spam-protection)
6. [ Customizing the generated honeypot fields ](#content-customizing-the-generated-honeypot-fields)
7. [ Events fired ](#content-events-fired)
8. [ Request handling and differences from PHP and Rust ](#content-request-handling-and-differences-from-php-and-rust)

First, add the `honeypot` template function to any form you wish to protect:

```
<form method="POST" action="/contact">
    {{csrfField}}
    {{honeypot}}
    <input name="email" type="email">
</form>
```

This adds two fields, `my_name_<random>` and `valid_from`. You can change the names in the package configuration. Keep the normal session and CSRF middleware on browser routes.

Next, use the `ProtectAgainstSpam` middleware on the route that handles the form submission:

```
route.Post("/contact", func(r *web.Request) *web.Response {
    return web.Text("Thanks for your message!")
}).Middleware(honeypot.ProtectAgainstSpam{})
```

The middleware discards requests with a nonempty honeypot value or a form submitted before the encrypted timestamp. Only POST requests are checked. The minimum age boundary is inclusive and uses Go's time precision rather than rounding to seconds. Keep server clocks synchronized.

The default permits a form with neither field, matching PHP. Set `cfg.FieldsRequired = true` on login, registration and other sensitive routes. If either protection field is present, the complete pair must be valid. With timing disabled, only the empty trap is checked.

To cover a route group, use `route.Middleware(honeypot.ProtectAgainstSpam{})`. To cover every web route, append it to the web stack:

```
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
    m.Web.Append(honeypot.ProtectAgainstSpam{})
},
```

Usage in Inertia
--------------------------------------------------------------------------------------------------------

When using Inertia, manually pass the values used in the honeypot fields:

```
fields, err := honeypot.From(r).Fields(r)
if err != nil {
    return web.Fail(err)
}
return inertia.Render("Contact", inertia.Props{"honeypot": fields})
```

Your frontend gets an object with `enabled`, `nameFieldName`, `unrandomizedNameFieldName`, `validFromFieldName` and `encryptedValidFrom` keys. Initialize the form with an empty string under `nameFieldName` and `encryptedValidFrom` under `validFromFieldName`. Keep those values together until submission.

Here's how these values could be rendered using Vue:

```
<div v-if="honeypot.enabled" hidden aria-hidden="true">
    <input :name="honeypot.nameFieldName" v-model="form[honeypot.nameFieldName]" type="text" autocomplete="off" tabindex="-1">
    <input :name="honeypot.validFromFieldName" v-model="form[honeypot.validFromFieldName]" type="text" autocomplete="off" tabindex="-1">
</div>
```

```
const form = useForm({
    email: '',
    [props.honeypot.nameFieldName]: '',
    [props.honeypot.validFromFieldName]: props.honeypot.encryptedValidFrom,
})
```

The backend accepts JSON, URL-encoded forms and multipart forms. The blank default response may not give an Inertia client useful feedback. Configure a responder returning a status or redirect appropriate to your frontend.

### Usage with Jetstream

Jetstream is a PHP application starter and is not part of Laravel Go. For a Go Inertia login or registration form, pass `Fields` as above and attach the middleware to its POST route. Set `FieldsRequired = true` and retain authentication, CSRF and rate limiting.

Usage in Livewire
-----------------------------------------------------------------------------------------------------------

Livewire's PHP traits and Blade components do not run in Go. Use the template function in server-rendered Go forms, or pass `Fields` to your frontend. For a stateful component handler, submit the field pair and call `honeypot.From(r).Check(r, input)` with the complete input map. Handle `errors.Is(err, honeypot.ErrSpam)` explicitly. A direct check does not dispatch middleware events or invoke the responder.

### Usage with a Content Security Policy

The default fields are hidden with the HTML `hidden` attribute instead of an inline style. No nonce or `HONEYPOT_WITH_CSP` option is needed, and no CSP package is required. Do not override `[hidden]` to make these fields visible in your stylesheets.

### Usage in Volt functional syntax

Volt is a PHP Livewire integration and has no Go equivalent. Use the direct `Check` API for component-style handlers as described above. There is no field-property guessing in Go.

Disabling in testing
--------------------------------------------------------------------------------------------------------------------

By default, a protected form submitted in less than one second is marked as spam. To disable generation and checking, set `HONEYPOT_ENABLED=false` or configure:

```
honeypot.New(func(cfg *honeypot.Config) {
    cfg.Enabled = false
})
```

To disable timing only, set `cfg.ValidFromTimestamp = false`. To test the real timing behavior, use Laravel's `client.Freeze()` and `client.Travel(time.Second)` rather than sleeping.

Customizing the response
--------------------------------------------------------------------------------------------------------------------------------

When a spammy submission is detected, the package shows a blank page by default. Supply your own responder to change that behavior:

```
honeypot.New(func(cfg *honeypot.Config) {
    cfg.Responder = func(r *web.Request, next web.Next) *web.Response {
        return web.Text("Please reload this form.").WithStatus(422)
    }
})
```

A responder may inspect the request to determine the source of spam. Do not log raw form values or encrypted tokens. If the package wrongly determined that the request is spammy, call `next(r)` to generate the regular response, like you would in middleware.

Customizing the spam protection
-----------------------------------------------------------------------------------------------------------------------------------------------------

The PHP `spam_protection` class is replaced with a Go `Checker` interface:

```
type Checker interface {
    Check(context.Context, map[string]any) error
}
```

Set `cfg.Checker` to an application-owned implementation. It replaces the complete checking policy. Return nil to accept, or return or wrap `honeypot.ErrSpam` to reject. Other errors become application failures and do not trigger the spam responder. Implementations must be safe for concurrent requests and must not change the input map. The `Enabled` switch still disables checking.

Do not register a second service of the same type to override the checker. Laravel Go v0.1.0 returns the first matching service. Use the explicit configuration field so the replacement is used by both middleware and direct checks.

Customizing the generated honeypot fields
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Publish the embedded view with Laravel's native command:

```
laravel vendor:publish honeypot honeypotFormFields
```

Edit `resources/views/vendor/honeypot/honeypotFormFields.html`. This is the default content:

```
{{if .Enabled}}<div id="{{.NameFieldName}}_wrap" hidden aria-hidden="true">
    <input id="{{.NameFieldName}}" name="{{.NameFieldName}}" type="text" value="" autocomplete="off" tabindex="-1">
    <input name="{{.ValidFromFieldName}}" type="text" value="{{.EncryptedValidFrom}}" autocomplete="off" tabindex="-1">
</div>{{end}}
```

The `honeypot` helper and `honeypot.From(r).Render(r)` both use this overridable view. You can also call `Fields(r)` and use your own template. Keep normal attribute escaping in place. Only trusted application views should return safe HTML.

Events fired
--------------------------------------------------------------------------------------------

Whenever middleware detects spam, it dispatches `honeypot.SpamDetectedEvent`. It has the live `Request` and the checking error as `Reason`. Register listeners through Laravel's native events:

```
Listeners: []laravel.Listener{
    laravel.Listen(func(ctx context.Context, e honeypot.SpamDetectedEvent) error {
        // Record safe metadata such as e.Request.URL.Path, not the request body.
        return nil
    }),
},
```

The event runs before the responder. Listener errors propagate as application errors. The request is valid only during its HTTP lifecycle. Do not retain it, serialize it into a job or expose it in JSON.

Request handling and differences from PHP and Rust
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

- Only nil and exactly empty strings pass the trap. Whitespace, `"0"`, numbers, booleans, objects, lists and uploaded files do not.
- URL-encoded and JSON checking uses the raw body after Laravel validates its size and field limits. Query parameters cannot supply missing body fields. URL-encoded duplicate trap or token names fail checking. Duplicate JSON members fail with 400 through the framework's strict decoder. JSON must be an object.
- Multipart input uses Laravel's native parser and binder, preserving uploaded files for downstream handlers. It sees the framework's normalized values and cannot recover duplicate scalars already discarded by the parser or whitespace trimmed to null. Configure normalization for multipart forms when those distinctions matter.
- Malformed bodies return 400, oversized bodies return 413 and unsupported body content types return 415. These are request errors, not spam events. A rejected spam submission returns an empty 200 unless you configure a responder.
- Field matching accepts the base name and underscore-prefixed randomized names, not every string sharing the PHP field prefix. Multiple trap candidates and bracketed protection fields fail. Field names are validated at startup. Generated names and tokens are bound together, so a token from one randomized form cannot be used with another name.
- Tokens authenticate a package purpose and configurable scope. They are not wire-compatible with PHP or Rust tokens. Like PHP, there is no maximum age. Unlike the Rust port, required fields are off by default and there is no validation-rule adapter. Use middleware or `Check`.
- There are no models or queued jobs in the PHP package to replace. Checker, responder and view replacements cover its extension points. Blade directives, Livewire traits, Volt and Jetstream remain PHP-specific.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
