Skip to Content
GoGo Routing

Last Updated: 3/9/2026


PocketBase v0.36.6

Routing

PocketBase routing is built on top of the standard Go net/http.ServeMux. The router can be accessed via the app.OnServe() hook allowing you to register custom endpoints and middlewares.

Routes

Registering new routes

Every route has a path, handler function and eventually middlewares attached to it. For example:

. OnServe(). BindFunc(func(*.) error{// register "GET /hello/{name}" route (allowed for everyone).. GET("/hello/{name}", func(*.) error{:=.. PathValue("name") return. String(., "Hello " +)})// register "POST /api/myapp/settings" route (allowed only for authenticated users).. POST("/api/myapp/settings", func(*.) error{// do something ... return. JSON(., map[string] bool{"success": true})}). Bind(. RequireAuth()) return. Next()})

There are several routes registration methods available, but the most common ones are:

.. GET(,).. POST(,).. PUT(,).. PATCH(,).. DELETE(,)// If you want to handle any HTTP method define only a path (e.g. "/example")// OR if you want to specify a custom one add it as prefix to the path (e.g. "TRACE /example").. Any(,)

The router also supports creating groups for routes that share the same base path and middlewares. For example:

:=.. Group("/api/myapp")// group middleware. Bind(. RequireAuth())// group routes. GET("",). GET("/example/{id}",). PATCH("/example/{id}",). BindFunc(/* custom route specific middleware func */)// nested group:=. Group("/sub"). GET("/sub1",)

The example registers the following endpoints
(all require authenticated user access):

  • GET /api/myapp -> action1
  • GET /api/myapp/example/{id} -> action2
  • PATCH /api/myapp/example/{id} -> action3
  • GET /api/myapp/example/sub/sub1 -> action4

Each router group and route could define middlewares in a similar manner to the regular app hooks via the Bind/BindFunc methods, allowing you to perform various BEFORE or AFTER action operations (e.g. inspecting request headers, custom access checks, etc.).

Path parameters and matching rules

Because PocketBase routing is based on top of the Go standard router mux, we follow the same pattern matching rules. Below you could find a short overview but for more details please refer to net/http.ServeMux.

In general, a route pattern looks like [METHOD ][HOST]/[PATH] (the METHOD prefix is added automatically when using the designated GET(), POST(), etc. methods)).

Route paths can include parameters in the format {paramName}.
You can also use {paramName...} format to specify a parameter that targets more than one path segment.

A pattern ending with a trailing slash / acts as anonymous wildcard and matches any requests that begins with the defined route. If you want to have a trailing slash but to indicate the end of the URL then you need to end the path with the special {$} parameter.

If your route path starts with /api/ consider combining it with your unique app name like /api/myapp/... to avoid collisions with system routes.

Here are some examples:

// match "GET example.com/index.html".. GET("example.com/index.html")// match "GET /index.html" (for any host).. GET("/index.html")// match "GET /static/", "GET /static/a/b/c", etc... GET("/static/")// match "GET /static/", "GET /static/a/b/c", etc.// (similar to the above but with a named wildcard parameter).. GET("/static/{path...}")// match only "GET /static/" (if no "/static" is registered, it is 301 redirected).. GET("/static/{$}")// match "GET /customers/john", "GET /customers/jane", etc... GET("/customers/{name}")


In the following examples e is usually *core.RequestEvent value.


Reading path parameters

:=.. PathValue("id")

Retrieving the current auth state

The request auth state can be accessed (or set) via the RequestEvent.Auth field.

:=.:=. == nil// the same as "e.Auth != nil && e.Auth.IsSuperuser()":=. HasSuperuserAuth()

Alternatively you could also access the request data from the summarized request info instance (usually used in hooks like the OnRecordEnrich where there is no direct access to the request) .

,:=. RequestInfo():=.:=. == nil// the same as "info.Auth != nil && info.Auth.IsSuperuser()":=. HasSuperuserAuth()

Reading query parameters

// retrieve the first value of the "search" query param:=... Query(). Get("search")// or via the parsed request info,:=. RequestInfo():=.["search"]// in case of array query params (e.g. search=123&search=456):=... Query()["search"]// []string{"123", "456"}

Reading request headers

:=... Get("Some-Header")// or via the parsed request info// (the header value is always normalized per the @request.headers.* API rules format),:=. RequestInfo():=.["some_header"]

Writing response headers

.. Header(). Set("Some-Header", "123")

Retrieving uploaded files

// retrieve the uploaded files and parse the found multipart data into a ready-to-use []*filesystem.File,:=. FindUploadedFiles("document")// or retrieve the raw single multipart/form-data file and header,,:=.. FormFile("document")

Reading request body

Body parameters can be read either via e.BindBody OR through the parsed request info (requires manual type assertions).

The e.BindBody argument must be a pointer to a struct or map[string]any.
The following struct tags are supported (the specific binding rules and which one will be used depend on the request Content-Type):

  • json (json body)- uses the builtin Go JSON package for unmarshaling.
  • xml (xml body) - uses the builtin Go XML package for unmarshaling.
  • form (form data) - utilizes the custom router.UnmarshalRequestData method.

NB! When binding structs make sure that they don’t have public fields that shouldn’t be bindable and it is advisable such fields to be unexported or define a separate struct with just the safe bindable fields.

// read/scan the request body fields into a typed struct:= struct{// unexported to prevent binding string stringjson:“title” form:“title” stringjson:“description” form:“description” booljson:“active” form:“active”}{} if:=. BindBody(&);!= nil{return. BadRequestError("Failed to read request data",)}// alternatively, read the body via the parsed request info,:=. RequestInfo(),:=.["title"].(string)

Writing response body

For all supported methods, you can refer to router.Event .

// send response with JSON body// (it also provides a generic response fields picker/filter if the "fields" query parameter is set). JSON(., map[string]{"name": "John"})// send response with string body. String(.,"Lorem ipsum...")// send response with HTML body// (check also the "Rendering templates" section). HTML(.,"Hello!")// redirect. Redirect(.,"https://example.com")// send response with no body. NoContent(.)// serve a single file. FileFS(. DirFS("..."),"example.txt")// stream the specified reader. Stream(.,"application/octet-stream",)// send response with blob (bytes slice) body. Blob(.,"application/octet-stream",[] byte{...})

Reading the client IP

// The IP of the last client connecting to your server.// The returned IP is safe and can be always trusted.// When behind a reverse proxy (e.g. nginx) this method returns the IP of the proxy.// https://pkg.go.dev/github.com/pocketbase/pocketbase/tools/router#Event.RemoteIP:=. RemoteIP()// The "real" IP of the client based on the configured Settings.TrustedProxy header(s).// If such headers are not set, it fallbacks to e.RemoteIP().// https://pkg.go.dev/github.com/pocketbase/pocketbase/core#RequestEvent.RealIP:=. RealIP()

Request store

The core.RequestEvent comes with a local store that you can use to share custom data between middlewares and the route action.

// store for the duration of the request. Set("someKey", 123)// retrieve later:=. Get("someKey").(int)// 123

Middlewares

Registering middlewares

Middlewares allow inspecting, intercepting and filtering route requests.

All middleware functions share the same signature with the route actions (aka. func(e *core.RequestEvent) error) but expect the user to call e.Next() if they want to proceed with the execution chain.

Middlewares can be registered globally, on group and on route level using the Bind and BindFunc methods.

Here is a minimal example of what a global middleware looks like:

. OnServe(). BindFunc(func(*.) error{// register a global middleware.. BindFunc(func(*.) error{if... Get("Something") == ""{return. BadRequestError("Something header value is missing!", nil)} return. Next()}) return. Next()})

RouterGroup.Bind(middlewares...) / Route.Bind(middlewares...) registers one or more middleware handlers.
Similar to the other app hooks, a middleware handler has 3 fields:

  • Id (optional) - the name of the middleware (could be used as argument for Unbind)
  • Priority (optional) - the execution order of the middleware (if empty fallbacks to the order of registration in the code)
  • Func (required) - the middleware handler function

Often you don’t need to specify the Id or Priority of the middleware and for convenience you can instead use directly RouterGroup.BindFunc(funcs...) / Route.BindFunc(funcs...) .

Below is a slightly more advanced example showing all options and the execution sequence (2,0,1,3,4):

. OnServe(). BindFunc(func(*.) error{// attach global middleware.. BindFunc(func(*.) error{println(0) return. Next()}):=.. Group("/sub")// attach group middleware. BindFunc(func(*.) error{println(1) return. Next()})// attach group middleware with an id and custom priority. Bind(&.[*.]{: "something",: func(*.) error{println(2) return. Next()},: - 1,})// attach middleware to a single route//// "GET /sub/hello" should print the sequence: 2,0,1,3,4. GET("/hello", func(*.) error{println(4) return. String(200,"Hello!")}). BindFunc(func(*.) error{println(3) return. Next()}) return. Next()})

Removing middlewares

To remove a registered middleware from the execution chain for a specific group or route you can make use of the Unbind(id) method.

Note that only middlewares that have a non-empty Id can be removed.

. OnServe(). BindFunc(func(*.) error{// global middleware.. Bind(&.[*.]{: "test",: func(*.) error{// ... return. Next()},)// "GET /A" invokes the "test" middleware.. GET("/A", func(*.) error{return. String(200, "A")})// "GET /B" doesn't invoke the "test" middleware.. GET("/B", func(*.) error{return. String(200, "B")}). Unbind("test") return. Next()})

Builtin middlewares

The apis package exposes several middlewares that you can use as part of your application.

// Require the request client to be unauthenticated (aka. guest).// Example: Route.Bind(apis.RequireGuestOnly()). RequireGuestOnly()// Require the request client to be authenticated// (optionally specify a list of allowed auth collection names, default to any).// Example: Route.Bind(apis.RequireAuth()). RequireAuth(...)// Require the request client to be authenticated as superuser// (this is an alias for apis.RequireAuth(core.CollectionNameSuperusers)).// Example: Route.Bind(apis.RequireSuperuserAuth()). RequireSuperuserAuth()// Require the request client to be authenticated as superuser OR// regular auth record with id matching the specified route parameter (default to "id").// Example: Route.Bind(apis.RequireSuperuserOrOwnerAuth("")). RequireSuperuserOrOwnerAuth()// Changes the global 32MB default request body size limit (set it to 0 for no limit).// Note that system record routes have dynamic body size limit based on their collection field types.// Example: Route.Bind(apis.BodyLimit(10 << 20)). BodyLimit()// Compresses the HTTP response using Gzip compression scheme.// Example: Route.Bind(apis.Gzip()). Gzip()// Instructs the activity logger to log only requests that have failed/returned an error.// Example: Route.Bind(apis.SkipSuccessActivityLog()). SkipSuccessActivityLog()

Default globally registered middlewares

The below list is mostly useful for users that may want to plug their own custom middlewares before/after the priority of the default global ones, for example: registering a custom auth loader before the rate limiter with apis.DefaultRateLimitMiddlewarePriority - 1 so that the rate limit can be applied properly based on the loaded auth state.

All PocketBase applications have the below internal middlewares registered out of the box (sorted by their priority):

Error response

PocketBase has a global error handler and every returned error from a route or middleware will be safely converted by default to a generic ApiError to avoid accidentally leaking sensitive information (the original raw error message will be visible only in the Dashboard > Logs or when in --dev mode).

To make it easier returning formatted JSON error responses, the request event provides several ApiError methods.
Note that ApiError.RawData() will be returned in the response only if it is a map of router.SafeErrorItem/validation.Error items.

import"github.com/go-ozzo/ozzo-validation/v4".. GET("/example", func(*.) error{...// construct ApiError with custom status code and validation data error return. Error(500, "something went wrong", map[string].{"title":. NewError("invalid_title", "Invalid or missing title"),})// if message is empty string, a default one will be set return. BadRequestError(,)// 400 ApiError return. UnauthorizedError(,)// 401 ApiError return. ForbiddenError(,)// 403 ApiError return. NotFoundError(,)// 404 ApiError return. TooManyRequestsError(,)// 429 ApiError return. InternalServerError(,)// 500 ApiError})

This is not very common but if you want to return ApiError outside of request related handlers, you can use the below apis.* factories:

import("github.com/go-ozzo/ozzo-validation/v4""github.com/pocketbase/pocketbase/apis"). OnRecordCreate(). BindFunc(func(*.) error{...// construct ApiError with custom status code and validation data error return. NewApiError(500, "something went wrong", map[string].{"title":. NewError("invalid_title", "Invalid or missing title"),})// if message is empty string, a default one will be set return. NewBadRequestError(,)// 400 ApiError return. NewUnauthorizedError(,)// 401 ApiError return. NewForbiddenError(,)// 403 ApiError return. NewNotFoundError(,)// 404 ApiError return. NewTooManyRequestsError(,)// 429 ApiError return. NewInternalServerError(,)// 500 ApiError})

Helpers

Serving static directory

apis.Static() serves static directory content from fs.FS instance.

Expects the route to have a {path...} wildcard parameter.

. OnServe(). BindFunc(func(*.) error{// serves static files from the provided dir (if exists).. GET("/{path...}",. Static(. DirFS("/path/to/public"), false)) return. Next()})

Auth response

apis.RecordAuthResponse() writes standardized JSON record auth response (aka. token + record data) into the specified request body. Could be used as a return result from a custom auth route.

. OnServe(). BindFunc(func(*.) error{.. POST("/phone-login", func(*.) error{:= struct{stringjson:“phone” form:“phone” stringjson:“password” form:“password”}{} if:=. BindBody(&);!= nil{return. BadRequestError("Failed to read request data",)},:=.. FindFirstRecordByData("users", "phone",.) if!= nil ||!. ValidatePassword(.){// return generic 400 error as a basic enumeration protection return. BadRequestError("Invalid credentials",)} return. RecordAuthResponse(,, "phone", nil)}) return. Next()})

Enrich record(s)

apis.EnrichRecord() and apis.EnrichRecords() helpers parses the request context and enrich the provided record(s) by:

  • expands relations (if defaultExpands and/or ?expand query parameter is set)
  • ensures that the emails of the auth record and its expanded auth relations are visible only for the current logged superuser, record owner or record with manage access

. OnServe(). BindFunc(func(*.) error{.. GET("/custom-article", func(*.) error{,:=.. FindRecordsByFilter("article","status = 'active'","-created", 40, 0) if!= nil{return. NotFoundError("No active articles",)}// enrich the records with the "categories" relation as default expand =. EnrichRecords(,, "categories") if!= nil{return} return. JSON(.,)}) return. Next()})

Go http.Handler wrappers

If you want to register standard Go http.Handler function and middlewares, you can use apis.WrapStdHandler(handler) and apis.WrapStdMiddleware(func) functions.

Sending request to custom routes using the SDKs

The official PocketBase SDKs expose the internal send() method that could be used to send requests to your custom route(s).

import from 'pocketbase'; const = new PocketBase('http://127.0.0.1:8090'); await. send("/hello",{// for other options check// https://developer.mozilla.org/en-US/docs/Web/API/fetch#options query:{"abc": 123},});

import'package:pocketbase/pocketbase.dart''package:pocketbase/pocketbase.dart'; final = PocketBase('http://127.0.0.1:8090''http://127.0.0.1:8090'); await. send("/hello""/hello",:{"abc" "abc": 123})


Prev: Event hooks Next: Database