Security 11 min read Markdown

Laravel Go Security Guide: Safe Defaults, Conventions and the Gaps Between Them

Laravel Go entered beta on 2 December 2026. It binds SQL parameters and escapes templates by default, but several protections that the Rust version enforces at compile time are conventions in Go. This guide covers the defaults to change and the conventions to enforce in review.

Matt King
Matt King
December 2, 2026
Last updated: December 6, 2026
Laravel Go Security Guide: Safe Defaults, Conventions and the Gaps Between Them

Laravel Go entered beta on 2 December 2026, a day after Laravel Rust. It is built directly on Go's standard net/http and database/sql, with no third-party web framework underneath, and it keeps Laravel's shape: routes, middleware groups, models, validation, queues.

Its security model is close to the Rust version's, with one important difference. Laravel says Go "trades a bit of the 'magic' syntax, macros, and raw top-end speed". For security that trade means several guarantees that are compile errors in Laravel Rust are conventions in Laravel Go. Conventions hold only if someone checks them.

This guide follows the official 0.x documentation as of 6 December 2026 (v0.2.0, Go 1.27 or later). It is a beta; verify anything you depend on.

The short version

Area Out of the box What you still do
SQL injection ? placeholders are bound Keep user input out of *Raw strings; allowlist column names
XSS html/template contextual escaping Audit every template.HTML; add a CSP
Password hash exposure Convention: json:"-" Test that responses never include it
Mass assignment Convention: validate into a form struct Never validate into a model
Form authorisation Optional Authorize method Require it in review
CORS Any origin on api/* Restrict and anchor origin patterns
Security headers Two headers only Add HSTS, CSP and the rest
Rate limiting None by default Throttle login, reset and API routes
Dependencies Nothing built in govulncheck and npm audit in CI

Three conventions to enforce

These are the places where Laravel Go relies on you.

1. Hide the password hash. The user model in the docs tags the field:

Password        string     `json:"-"`

and explains why: "Without it, those responses would send the user's password hash to the browser". Nothing fails if the tag is missing. Write one test that returns a user as JSON and asserts the hash is not in the body.

2. Never validate into a model. Validation uses a plain struct with a Rules() method and r.Validate[StorePost](). The docs warn: "Never validate request input directly into a model struct, as that would allow clients to populate sensitive columns such as votes or is_admin." This is mass assignment in Go form, and no compiler stops it.

3. Authorise every form. A form type may have an Authorize method, but it is optional. In Laravel Rust, omitting the decision is a build failure. In Go, an endpoint with rules and no authorisation runs happily. Make "where is the authorisation?" a standing review question, and scope queries to the current user to avoid IDOR.

Environment and secrets

  • APP_ENV defaults to production when unset, and "debug mode is off unless you turn it on". Both fail safe.
  • APP_DEBUG=true shows a lot. The debug page includes the error and its Go type, the source around the failing line, wrapped errors, "the request's headers and route", and the stack for a panic. JSON responses gain error and trace keys. The page leaves out the Cookie and Authorization headers, but every other header is shown, including the ones your proxy adds, such as internal addresses and custom authentication headers. Keep it off in production.
  • APP_KEY encrypts cookies and sessions. Whoever has it can decrypt values, forge cookies and create signed URLs. One key per environment; rotate with APP_PREVIOUS_KEYS.
  • .env values reach every library. Laravel Go "copies the .env file's variables into the process's environment, so a library that calls os.Getenv ... sees them too". Convenient, and a reason to keep the dependency list short: any package in the process can read every secret.

SQL: bound values, verbatim raw strings

db.Select, db.SelectOne and db.Exec take ? placeholders, and the docs state that "Laravel binds each value as a query parameter, so a value can never inject SQL". Lists go through db.In(slice).

The raw builder methods are different. SelectRaw, WhereRaw, OrWhereRaw, HavingRaw, OrderByRaw and db.Raw embed "a raw expression's SQL in the query verbatim". Used properly, input still goes through a placeholder:

db.Table("users").WhereRaw("email ~* ?", pattern)

Used badly, with fmt.Sprintf or string concatenation, it is a textbook injection. Grep for them:

grep -rnE "(Select|Where|OrWhere|Having|OrderBy)Raw\(|db\.Raw\(|\.Pool\(\)|db\.From\(" --include=*.go .

db.From(r) and Pool() drop down to database/sql and send "the SQL to the driver as written".

Column names are strings. Because the builder takes names like .Where("api_token", "=", ...), a sort or filter parameter taken from the request can reach a column name. Laravel quotes identifiers, so this is not injection, but the docs warn it "can still expose columns users shouldn't be able to read or sort by. Always validate user-supplied column names against an explicit allowlist". Sorting by password one character at a time is a real data leak.

XSS and Content Security Policy

Views are Go's html/template, which escapes by context: HTML body, attribute, URL and script positions are each handled correctly. A javascript: link typed by a user renders as #ZgotmplZ. The unescaped path is passing a template.HTML value from the handler. Treat every template.HTML(...) conversion like {!! !!} in Blade.

The framework's own helpers are young. A fix merged on 3 December closed a case where the template merge helper emitted href="javascript:..." unescaped. Stay on the latest 0.x tag.

No CSP is set by default. The Vite integration supports a per-request nonce (vite.WithCSPNonce and {{cspNonce}} in templates) for a policy you add in middleware.

CSRF

ValidateCSRFToken runs on the web group for every method except GET, HEAD and OPTIONS. A request marked same-origin by Sec-Fetch-Site passes; anything else needs the session token or gets 419. Always send the token, because browsers omit Sec-Fetch-Site over plain HTTP.

The docs are explicit that "the api group is empty". No session, no CSRF, no authentication, no throttle. Everything an API route needs, you attach.

Exclusions are a struct field:

middleware.ValidateCSRFToken{Except: []string{"webhooks/*"}}

Keep the list to machine-called routes and verify each by signature.

Sessions and cookies

Defaults: SameSite=lax, HttpOnly, 120 minutes, ID regenerated on login. Points to check:

  • Set SESSION_DRIVER explicitly. The fallback when unset is cookie, where "a copy of an old session cookie remains valid until it expires".
  • SESSION_ENCRYPT is false in the example config. Enable it if sessions hold sensitive data.
  • In Laravel Go the Secure flag is set "when the request arrived over HTTPS". Behind a TLS-terminating load balancer that depends on trusted proxies being configured. Get that wrong and session cookies go out without Secure. Verify with a cookie check.
  • Cookies set outside the web group are sent unencrypted.

Two open pull requests propose hardening here (session handling when EncryptCookies is omitted, and constant-time comparison of remember tokens). They were unmerged and unconfirmed when we checked. The practical advice is to leave the default web middleware stack intact.

CORS

The default lets any origin call api/*. Replace it in bootstrap/app.go:

m.Replace(middleware.HandleCORS{
	Paths:            []string{"api/*"},
	AllowedOrigins:   []string{"https://app.example.com"},
	AllowCredentials: true,
	MaxAge:           time.Hour,
})

Two Go-specific traps from the docs. With AllowCredentials and no origin list, "any site may call your application as the signed-in visitor". And AllowedOriginPatterns are regular expressions that match any part of the origin unless anchored, so example\.com also matches example.com.attacker.net. Anchor with ^ and $. More in CORS misconfigurations.

Security headers

Only X-Frame-Options: SAMEORIGIN and X-Content-Type-Options: nosniff are set. The docs show wrapping a standard net/http middleware to add more:

headers := secure.New(secure.Options{
	ReferrerPolicy:    "strict-origin-when-cross-origin",
	PermissionsPolicy: "camera=(), microphone=(), geolocation=()",
})

m.Global.Append(web.WrapMiddleware(headers.Handler))

Add HSTS and a CSP the same way or at your proxy, then confirm with the header checker.

Authentication and rate limiting

  • Passwords use bcrypt at cost 12; over 72 bytes is rejected. Login is constant-time with respect to whether the account exists. Reset tokens are single-use and expire after 60 minutes.
  • There is no Sanctum or Passport equivalent. API authentication is a request guard you write, registered with auth.Via(...), and the docs say to store a hash of each token.
  • No route is rate limited by default, login included. Add throttles to authentication and API routes, and use the database or Redis cache store so limits hold across instances.

Go runtime hazards

Two behaviours come from Go itself and have availability consequences.

A panic in your own goroutine kills the process. Laravel recovers panics inside a request and returns 500. A goroutine you start with go func() is outside that recovery, and the docs warn that a panic there "ends the whole process". A nil map write in a background goroutine, triggered by crafted input, is a denial of service. Recover in every goroutine you spawn.

The timeout cannot stop your handler. The default 30-second deadline returns 503, but Laravel "can't stop your handler". Work that ignores context keeps running and holding its connections. Pass the request context to every database and HTTP call.

Proxies, hosts and endpoints

  • Trust your load balancer explicitly: m.Proxies = []string{"10.0.0.0/8"}. Otherwise the client IP is the proxy's, every visitor shares one rate-limit key and generated URLs start with http://.
  • In production only the APP_URL host and its subdomains are answered. This is off in local and testing.
  • /up is public, runs before middleware and does not check the database.
  • If you mount Prometheus at /metrics as the docs show, add authentication or keep it off the public listener. The example has none.
  • Reverb accepts any origin by default; set REVERB_APP_ALLOWED_ORIGINS.
  • Workflow wait tokens are "an identifier, not a secret". Authenticate resume routes.

Dependencies

go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
npm audit --omit=dev

govulncheck reports only vulnerabilities in code paths you actually call, which keeps the noise low. Run it in CI alongside npm audit for the Inertia front end.

Checking from the outside

Headers, CORS, cookie flags, TLS and exposed files are all visible externally, whatever the language. Run a free scan on the deployed app, and read Laravel Go vs PHP security if you are deciding whether to move a service across.

Free security check

Is your Laravel app exposed right now?

34% of Laravel apps we scan have at least one critical issue, and most teams do not find out until something breaks. The free scan checks your live app in 60 seconds. Then StackShield re-runs every check after each deploy, so a fix you ship today does not quietly regress next week.

18% have debug mode on
72% missing security headers
12% have exposed .env
Scan My App Free No signup for the scan. Continuous monitoring on a 14-day trial, no card.

Frequently Asked Questions

Is Laravel Go production ready?

It is in beta. Laravel warns that releases before 1.0 may include breaking changes. As of 6 December 2026 there were no published security advisories for it, and one security fix (a template helper that emitted javascript: links unescaped) had been merged the day after launch. Use it with the caution any 0.x framework deserves.

Can a Laravel Go application have SQL injection?

Yes, through raw expressions. Values passed as ? placeholders are bound, but WhereRaw, SelectRaw, OrderByRaw and db.Raw embed their SQL string verbatim, and the escape hatches to database/sql send SQL as written. Building any of those strings from user input is an injection.

How do I stop a password hash appearing in a Laravel Go JSON response?

Tag the field with json:"-" on the model, as the docs show. Unlike Laravel Rust, nothing stops the build if you forget, so add a test that serialises a user and asserts the hash is absent.

Does Laravel Go set security headers?

Two: X-Frame-Options: SAMEORIGIN and X-Content-Type-Options: nosniff. HSTS, Content-Security-Policy, Referrer-Policy and Permissions-Policy are not set by default. The docs show adding some of them with the unrolled/secure package.

What should I use to scan Laravel Go dependencies?

Run govulncheck for the Go module graph and npm audit for the front end. The Laravel Go docs do not cover dependency auditing, so add both to CI yourself.

Stay Updated on Laravel Security

Get actionable security tips, vulnerability alerts, and best practices for Laravel apps.