### Start PocketBase Server Source: https://pocketbase.io/docs Run this command in the extracted directory to start the PocketBase application server. It will automatically generate an installer link for the superuser account. ```bash ./pocketbase serve ``` -------------------------------- ### Route Path Matching Examples Source: https://pocketbase.io/docs/go-routing Examples demonstrating various route path matching rules including specific paths, wildcards, and named parameters. ```go // match "GET example.com/index.html" se.Router.GET("example.com/index.html") // match "GET /index.html" (for any host) se.Router.GET("/index.html") // match "GET /static/", "GET /static/a/b/c", etc. se.Router.GET("/static/") // match "GET /static/", "GET /static/a/b/c", etc. // (similar to the above but with a named wildcard parameter) se.Router.GET("/static/{path...}") // match only "GET /static/" (if no "/static" is registered, it is 301 redirected) se.Router.GET("/static/{$}") // match "GET /customers/john", "GET /customers/jane", etc. se.Router.GET("/customers/{name}") ``` -------------------------------- ### Customize Server with OnServe Hook Source: https://pocketbase.io/docs/go-event-hooks The OnServe hook runs when the app web server starts, enabling route and middleware adjustments. This example registers a GET /hello route. ```go package main import ( "log" "net/http" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() app.OnServe().BindFunc(func(e *core.ServeEvent) error { // register new "GET /hello" route e.Router.GET("/hello", func(e *core.RequestEvent) error { return e.String(200, "Hello world!") }).Bind(apis.RequireAuth()) return e.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Start PocketBase Production HTTPS Server Source: https://pocketbase.io/docs/going-to-production Use this command to start a production HTTPS server with auto-managed TLS. Specify a domain name to issue a Let's Encrypt certificate. This command requires root privileges to bind to ports 80 and 443. ```bash [root@dev ~]$ /root/pb/pocketbase serve yourdomain.com ``` -------------------------------- ### Set and Get from App Store Source: https://pocketbase.io/docs/go-miscellaneous Demonstrates how to set and retrieve values from the application's concurrent-safe memory store. ```Go app.Store().Set("example", 123) v1 := app.Store().Get("example").(int) // 123 ``` -------------------------------- ### Execute Code on App Bootstrap Source: https://pocketbase.io/docs/js-overview This example demonstrates how to define a function that runs once when the PocketBase application initializes. It logs a message to the console after the app is ready. ```javascript onBootstrap((e) => { e.next() console.log("App initialized!") }) ``` -------------------------------- ### Create Superuser Manually Source: https://pocketbase.io/docs If the installer link does not open automatically, you can create the first superuser manually using this command, providing the desired email and password. ```bash ./pocketbase superuser create EMAIL PASS ``` -------------------------------- ### Registering a GET Route with Path Parameter Source: https://pocketbase.io/docs/js-routing This example shows how to register a GET route that accepts a path parameter named 'name'. The handler function extracts the 'name' from the path and returns a JSON response. ```APIDOC ## GET /hello/{name} ### Description Registers a GET route that greets a user by name. ### Method GET ### Endpoint /hello/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello John" } ``` ``` -------------------------------- ### Registering Custom Routes Source: https://pocketbase.io/docs/go-routing Demonstrates how to register GET and POST routes with optional authentication middleware. ```APIDOC ## Registering New Routes Every route has a path, handler function and eventually middlewares attached to it. For example: ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // register "GET /hello/{name}" route (allowed for everyone) se.Router.GET("/hello/{name}", func(e *core.RequestEvent) error { name := e.Request.PathValue("name") return e.String(http.StatusOK, "Hello " + name) }) // register "POST /api/myapp/settings" route (allowed only for authenticated users) se.Router.POST("/api/myapp/settings", func(e *core.RequestEvent) error { // do something ... return e.JSON(http.StatusOK, map[string]bool{"success": true}) }).Bind(apis.RequireAuth()) return se.Next() }) ``` There are several routes registration methods available, but the most common ones are: - `se.Router.GET(path, action)` - `se.Router.POST(path, action)` - `se.Router.PUT(path, action)` - `se.Router.PATCH(path, action)` - `se.Router.DELETE(path, action)` 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"). - `se.Router.Any(pattern, action)` ``` -------------------------------- ### Query Logs Source: https://pocketbase.io/docs/go-logging Use `app.LogQuery()` to build and execute custom queries for retrieving logs from the database. This example filters by level and request type, orders by creation date, and limits the results. ```go logs := []*core.Log{} // see https://pocketbase.io/docs/go-database/#query-builder err := app.LogQuery(). // target only debug and info logs AndWhere(dbx.In("level", -4, 0)). // the data column is serialized json object and could be anything AndWhere(dbx.NewExp("json_extract(data, '$.type') = 'request'")). OrderBy("created DESC"). Limit(100). All(&logs) ``` -------------------------------- ### Exporting Helper Module Source: https://pocketbase.io/docs/js-overview Example of how to export helper functions from a local module file (e.g., utils.js) for use in other hooks. ```javascript // pb_hooks/utils.js module.exports = { hello: (name) => { console.log("Hello " + name) } } ``` -------------------------------- ### Example View Collection SQL Query Source: https://pocketbase.io/docs/collections This SQL query demonstrates how to create a read-only view collection that aggregates post and comment data. ```sql SELECT posts.id, posts.name, count(comments.id) as totalComments FROM posts LEFT JOIN comments on comments.postId = posts.id GROUP BY posts.id ``` -------------------------------- ### Registering Custom Routes and Middlewares Source: https://pocketbase.io/docs/go-routing Register custom GET and POST routes with optional authentication middlewares. Use app.OnServe() to access the router. ```go se.Router.GET("/hello/{name}", func(e *core.RequestEvent) error { name := e.Request.PathValue("name") return e.String(http.StatusOK, "Hello " + name) }) se.Router.POST("/api/myapp/settings", func(e *core.RequestEvent) error { // do something... return e.JSON(http.StatusOK, map[string]bool{"success": true}) }).Bind(apis.RequireAuth()) ``` -------------------------------- ### Register Custom Route in JavaScript Source: https://pocketbase.io/docs/use-as-framework Register a custom HTTP GET route '/hello' that returns 'Hello world!' using JavaScript. This is a direct equivalent to the Go snippet. ```javascript routerAdd("GET", "/hello", (e) => { return e.string(200, "Hello world!") }) ``` -------------------------------- ### Register Custom Route in Go Source: https://pocketbase.io/docs/use-as-framework Use this snippet to register a custom HTTP GET route '/hello' that returns 'Hello world!'. It binds to the OnServe event. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { se.Router.GET("/hello", func(e *core.RequestEvent) error { return e.String(http.StatusOK, "Hello world!") }) return se.Next() }) ``` -------------------------------- ### Systemd Service for PocketBase Source: https://pocketbase.io/docs/going-to-production A Systemd service file to manage the PocketBase application, ensuring it starts on boot and restarts automatically if it crashes. Configure `WorkingDirectory`, `ExecStart`, and log file paths as needed. ```ini [Unit] Description = pocketbase [Service] Type = simple User = root Group = root LimitNOFILE = 4096 Restart = always RestartSec = 5s StandardOutput = append:/root/pb/std.log StandardError = append:/root/pb/std.log WorkingDirectory = /root/pb ExecStart = /root/pb/pocketbase serve yourdomain.com [Install] WantedBy = multi-user.target ``` -------------------------------- ### Initialize Default Application Settings Source: https://pocketbase.io/docs/go-migrations This snippet demonstrates how to set default application settings like app name, URL, and log retention policies. It's useful for establishing initial configurations. ```go // migrations/1687801090_initial_settings.go package migrations import ( "github.com/pocketbase/pocketbase/core" m "github.com/pocketbase/pocketbase/migrations" ) func init() { m.Register(func(app core.App) error { settings := app.Settings() // for all available settings fields you could check // https://github.com/pocketbase/pocketbase/blob/develop/core/settings_model.go#L121-L130 settings.Meta.AppName = "test" settings.Meta.AppURL = "https://example.com" settings.Logs.MaxDays = 2 settings.Logs.LogAuthId = true settings.Logs.LogIP = false return app.Save(settings) }, nil) } ``` -------------------------------- ### Example Post Record with Expanded Comments Source: https://pocketbase.io/docs/working-with-relations This JSON represents a sample post record returned by PocketBase, demonstrating how back-relations and their expanded related data (like user details for comments) are structured. ```json { "page": 1, "perPage": 30, "totalPages": 2, "totalItems": 45, "items": [ { "id": "WyAw4bDrvws6gGl", "collectionId": "1rAwHJatkTNCUIN", "collectionName": "posts", "created": "2022-01-01 01:00:00.456Z", "updated": "2022-01-01 02:15:00.456Z", "title": "Lorem ipsum dolor sit...", "expand": { "comments_via_post": [ { "id": "lmPJt4Z9CkLW36z", "collectionId": "BHKW36mJl3ZPt6z", "collectionName": "comments", "created": "2022-01-01 01:00:00.456Z", "updated": "2022-01-01 02:15:00.456Z", "post": "WyAw4bDrvws6gGl", "user": "FtHAW9feB5rze7D", "message": "lorem ipsum...", "expand": { "user": { "id": "FtHAW9feB5rze7D", "collectionId": "srmAo0hLxEqYF7F", "collectionName": "users", "created": "2022-01-01 00:00:00.000Z", "updated": "2022-01-01 00:00:00.000Z", "username": "users54126", "verified": false, "emailVisibility": false, "name": "John Doe" } } }, { "id": "tu4Z9CkLW36mPJz", "collectionId": "BHKW36mJl3ZPt6z", "collectionName": "comments", "created": "2022-01-01 01:10:00.123Z", "updated": "2022-01-01 02:39:00.456Z", "post": "WyAw4bDrvws6gGl", "user": "FtHAW9feB5rze7D", "message": "hello...", "expand": { "user": { "id": "FtHAW9feB5rze7D", "collectionId": "srmAo0hLxEqYF7F", "collectionName": "users", "created": "2022-01-01 00:00:00.000Z", "updated": "2022-01-01 00:00:00.000Z", "username": "users54126", "verified": false, "emailVisibility": false, "name": "John Doe" } } }, ... ] } }, ... ] } ``` -------------------------------- ### Autogenerate Text Field Example Source: https://pocketbase.io/docs/collections This example shows how to autogenerate a field value based on a pattern when submitting data. ```json {"slug:autogenerate":"abc-"} ``` -------------------------------- ### Delete Collection API Response Examples Source: https://pocketbase.io/docs/api-collections These are example responses for the delete collection API endpoint, illustrating successful operations and various error conditions. ```json { "id": "_pbc_2287844090", "listRule": null, "viewRule": null, "createRule": null, "updateRule": null, "deleteRule": null, "name": "posts", "type": "base", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", "hidden": false, "id": "text3208210256", "max": 15, "min": 15, "name": "id", "pattern": "^[a-z0-9]+$", "presentable": false, "primaryKey": true, "required": true, "system": true, "type": "text" }, { "autogeneratePattern": "", "hidden": false, "id": "text724990059", "max": 0, "min": 0, "name": "title", "pattern": "", "presentable": false, "primaryKey": false, "required": false, "system": false, "type": "text" }, { "hidden": false, "id": "autodate2990389176", "name": "created", "onCreate": true, "onUpdate": false, "presentable": false, "system": false, "type": "autodate" }, { "hidden": false, "id": "autodate3332085495", "name": "updated", "onCreate": true, "onUpdate": true, "presentable": false, "system": false, "type": "autodate" } ], "indexes": [], "system": false } ``` ```json { "status": 400, "message": "An error occurred while submitting the form.", "data": { "email": { "code": "validation_required", "message": "Missing required value." } } } ``` ```json { "status": 401, "message": "The request requires valid record authorization token.", "data": {} } ``` ```json { "status": 403, "message": "The authorized record is not allowed to perform this action.", "data": {} } ``` -------------------------------- ### Minimal PocketBase Go Application Source: https://pocketbase.io/docs/go-overview This snippet shows the basic structure for a PocketBase application using Go. It initializes a new app instance, registers a handler to serve static files, and starts the application. ```go package main import ( "log" "os" "github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/core" ) func main() { app := pocketbase.New() // serves static files from the provided public dir (if exists) app.OnServe().BindFunc(func(se *core.ServeEvent) error { se.Router.GET("/{path...}", apis.Static(os.DirFS("./pb_public"), false)) return se.Next() }) if err := app.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Serving Static Files with $apis.static Source: https://pocketbase.io/docs/js-routing Illustrates how to serve static files from a specified directory using the $apis.static helper. This requires a route with a wildcard path parameter. ```javascript routerAdd("GET", "/{path...}", $apis.static("/path/to/public", false)) ``` -------------------------------- ### Filter Expression Syntax Example Source: https://pocketbase.io/docs/api-rules-and-filters Illustrates the basic syntax of a filter expression, which follows the OPERAND OPERATOR OPERAND format. This example uses a datetime macro. ```plaintext @request.body.publicDate >= @now ``` -------------------------------- ### Register GET Route with Path Parameter Source: https://pocketbase.io/docs/js-routing Register a GET route that accepts a path parameter 'name'. The handler function extracts and uses this parameter to return a JSON response. ```javascript // register "GET /hello/{name}" route (allowed for everyone) routerAdd("GET", "/hello/{name}", (e) => { let name = e.request.pathValue("name") return e.json(200, { "message": "Hello " + name }) }) ``` -------------------------------- ### Register Group and Route Middlewares with Options Source: https://pocketbase.io/docs/go-routing Demonstrates registering global, group, and route-level middlewares with custom IDs and priorities. The execution order is shown in the comments. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // attach global middleware se.Router.BindFunc(func(e *core.RequestEvent) error { println(0) return e.Next() }) g := se.Router.Group("/sub") // attach group middleware g.BindFunc(func(e *core.RequestEvent) error { println(1) return e.Next() }) // attach group middleware with an id and custom priority g.Bind(&hook.Handler[*core.RequestEvent]{ Id: "something", Func: func(e *core.RequestEvent) error { println(2) return e.Next() }, Priority: -1, }) // attach middleware to a single route // // "GET /sub/hello" should print the sequence: 2,0,1,3,4 g.GET("/hello", func(e *core.RequestEvent) error { println(4) return e.String(200, "Hello!") }).BindFunc(func(e *core.RequestEvent) error { println(3) return e.Next() }) return se.Next() }) ``` -------------------------------- ### Initialize Default Application Settings Source: https://pocketbase.io/docs/js-migrations This snippet demonstrates how to set default application settings, including metadata like app name and URL, and logging configurations. Refer to the provided link for all available settings fields. ```javascript // pb_migrations/1687801090_initial_settings.js migrate((app) => { let settings = app.settings() // for all available settings fields you could check // /jsvm/interfaces/core.Settings.html settings.meta.appName = "test" settings.meta.appURL = "https://example.com" settings.logs.maxDays = 2 settings.logs.logAuthId = true settings.logs.logIP = false app.save(settings) }) ``` -------------------------------- ### Define a GET Route with Path Parameter Source: https://pocketbase.io/docs/js-overview This snippet demonstrates how to define a custom GET route with a path parameter using the `routerAdd` function. It extracts the 'name' from the URL and returns a JSON response. ```javascript routerAdd("GET", "/hello/{name}", (e) => { let name = e.request.pathValue("name") return e.json(200, { "message": "Hello " + name }) }) ``` -------------------------------- ### Get Record Field Value Source: https://pocketbase.io/docs/js-records Retrieve field values using `get()` or type-specific getters like `getBool()`, `getString()`, etc. Inspect unsaved files with `getUnsavedFiles()` and unmarshal JSON fields with `unmarshalJSONField()`. ```javascript record.get("someField") // -> any (without cast) record.getBool("someField") // -> cast to bool record.getString("someField") // -> cast to string record.getInt("someField") // -> cast to int record.getFloat("someField") // -> cast to float64 record.getDateTime("someField") // -> cast to types.DateTime record.getStringSlice("someField") // -> cast to []string record.getUnsavedFiles("someFileField") // unmarshal a single json field value into the provided result let result = new DynamicModel({ ... }) record.unmarshalJSONField("someJsonField", result) record.expandedOne("author") // -> as null|Record record.expandedAll("categories") // -> as []Record record.publicExport() ``` -------------------------------- ### Get Record Field Value in Go Source: https://pocketbase.io/docs/go-records Retrieve field values using `Get` with optional type casting methods like `GetBool`, `GetString`, `GetInt`, `GetFloat`, `GetDateTime`, and `GetStringSlice`. Inspect unsaved files with `GetUnsavedFiles` and unmarshal JSON fields with `UnmarshalJSONField`. ```go record.Get("someField") record.GetBool("someField") record.GetString("someField") record.GetInt("someField") record.GetFloat("someField") record.GetDateTime("someField") record.GetStringSlice("someField") record.GetUnsavedFiles("someFileField") record.UnmarshalJSONField("someJSONField", &result) ``` -------------------------------- ### Register Route with Host and Path Matching Source: https://pocketbase.io/docs/js-routing Demonstrates registering routes with specific host and path combinations, including exact matches and wildcard paths. ```javascript // match "GET example.com/index.html" routerAdd("GET", "example.com/index.html", ...) ``` ```javascript // match "GET /index.html" (for any host) routerAdd("GET", "/index.html", ...) ``` ```javascript // match "GET /static/", "GET /static/a/b/c", etc. routerAdd("GET", "/static/", ...) ``` ```javascript // match "GET /static/", "GET /static/a/b/c", etc. // (similar to the above but with a named wildcard parameter) routerAdd("GET", "/static/{path...}", ...) ``` ```javascript // match only "GET /static/" (if no "/static" is registered, it is 301 redirected) routerAdd("GET", "/static/{$}", ...) ``` ```javascript // match "GET /customers/john", "GET /customers/jane", etc. routerAdd("GET", "/customers/{name}", ...) ``` -------------------------------- ### View All PocketBase Commands Source: https://pocketbase.io/docs To see all available commands and their options for the PocketBase executable, use the --help flag. ```bash ./pocketbase --help ``` -------------------------------- ### Get Collection Scaffolds Source: https://pocketbase.io/docs/api-collections Retrieves the scaffold for a collection. Requires a valid Authorization token. ```json { "auth": { "id": "", "listRule": null, "viewRule": null, "createRule": null, "updateRule": null, "deleteRule": null, "name": "", "type": "auth", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", "hidden": false, "id": "text3208210256", "max": 15, "min": 15, "name": "id", "pattern": "^[a-z0-9]+$", "presentable": false, "primaryKey": true, "required": true, "system": true, "type": "text" }, { "cost": 0, "hidden": true, "id": "password901924565", "max": 0, "min": 8, "name": "password", "pattern": "", "presentable": false, "required": true, "system": true, "type": "password" }, { "autogeneratePattern": "[a-zA-Z0-9]{50}", "hidden": true, "id": "text2504183744", "max": 60, "min": 30, "name": "tokenKey", "pattern": "", "presentable": false, "primaryKey": false, "required": true, "system": true, "type": "text" }, { "exceptDomains": null, "hidden": false, "id": "email3885137012", "name": "email", "onlyDomains": null, "presentable": false, "required": true, "system": true, "type": "email" }, { "hidden": false, "id": "bool1547992806", "name": "emailVisibility", "presentable": false, "required": false, "system": true, "type": "bool" }, { "hidden": false, "id": "bool256245529", "name": "verified", "presentable": false, "required": false, "system": true, "type": "bool" } ], "indexes": [ "CREATE UNIQUE INDEX `idx_tokenKey_hclGvwhtqG` ON `test` (`tokenKey`)", "CREATE UNIQUE INDEX `idx_email_eyxYyd3gp1` ON `test` (`email`) WHERE `email` != ''" ], "created": "", "updated": "", "system": false, "authRule": "", "manageRule": null, "authAlert": { "enabled": true, "emailTemplate": { "subject": "Login from a new location", "body": "..." } }, "oauth2": { "providers": [], "mappedFields": { "id": "", "name": "", "username": "", "avatarURL": "" }, "enabled": false }, "passwordAuth": { "enabled": true, "identityFields": [ "email" ] }, "mfa": { "enabled": false, "duration": 1800, "rule": "" }, "otp": { "enabled": false, "duration": 180, "length": 8, "emailTemplate": { "subject": "OTP for {APP_NAME}", "body": "..." } }, "authToken": { "duration": 604800 }, "passwordResetToken": { "duration": 1800 }, "emailChangeToken": { "duration": 1800 }, "verificationToken": { "duration": 259200 }, "fileToken": { "duration": 180 }, "verificationTemplate": { "subject": "Verify your {APP_NAME} email", "body": "..." }, "resetPasswordTemplate": { "subject": "Reset your {APP_NAME} password", "body": "..." }, "confirmEmailChangeTemplate": { "subject": "Confirm your {APP_NAME} new email address", "body": "..." } }, "base": { "id": "", "listRule": null, "viewRule": null, "createRule": null, "updateRule": null, "deleteRule": null, "name": "", "type": "base", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", "hidden": false, "id": "text3208210256", "max": 15, "min": 15, "name": "id", "pattern": "^[a-z0-9]+$", "presentable": false, "primaryKey": true, "required": true, "system": true, "type": "text" } ], "indexes": [], "created": "", "updated": "", "system": false }, "view": { "id": "", "listRule": null, "viewRule": null, "createRule": null, "updateRule": null, "deleteRule": null, "name": "", "type": "view", "fields": [], "indexes": [], "created": "", "updated": "", "system": false, "viewQuery": "" } } ``` -------------------------------- ### GET /api/logs/stats Source: https://pocketbase.io/docs/api-logs Retrieves statistics for API logs. Supports filtering and field selection. ```APIDOC ## GET /api/logs/stats ### Description Retrieves statistics for API logs. This endpoint allows filtering logs based on various criteria and specifying which fields to return. ### Method GET ### Endpoint /api/logs/stats ### Query Parameters - **filter** (String) - Optional - Filter expression to filter/search the logs. Example: `?filter=(data.url~'test.com' && level>0)`. Supported log filter fields include `rowid`, `id`, `created`, `updated`, `level`, `message`, and any `data.*` attribute. Operators include `=`, `!=`, `>`, `>=`, `<`, `<=`, `~`, `!~`, `?=`, `?!==`, `?>`, `?>=`, `?<`, `?<=`, `?~`, `?!~`. Parentheses `(...)`, `&&` (AND), and `||` (OR) can be used for grouping. Single line comments `// Example comment` are also supported. Field expressions with array-like values or nested fields from multiple records default to a match-all constraint; use `?` prefix for any/at-least-one-of constraint (e.g., `multiRelation.title ?= "test"`). - **fields** (String) - Optional - Comma-separated string of fields to return. Defaults to all fields. Example: `?fields=*,expand.relField.name`. `*` targets all keys at the current depth. Supports `:excerpt(maxLength, withEllipsis?)` modifier for string fields to return a short plain text version. Example: `?fields=*,description:excerpt(200,true)`. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) Returns an array of log statistics objects, each containing 'total' and 'date'. Example: `[ { "total": 4, "date": "2022-06-01 19:00:00.000" }, { "total": 1, "date": "2022-06-02 12:00:00.000" }, { "total": 8, "date": "2022-06-02 13:00:00.000" } ]` #### Error Responses - **400 Bad Request**: `{ "status": 400, "message": "Something went wrong while processing your request. Invalid filter.", "data": {} }` - **401 Unauthorized**: `{ "status": 401, "message": "The request requires valid record authorization token.", "data": {} }` - **403 Forbidden**: `{ "status": 403, "message": "The authorized record is not allowed to perform this action.", "data": {} }` ``` -------------------------------- ### Create Initial Superuser Source: https://pocketbase.io/docs/go-migrations This migration creates the initial superuser account for the application. It sets the email and password, which can be overridden by environment variables or config files. Includes an optional revert operation. ```go // migrations/1687801090_initial_superuser.go package migrations import ( "github.com/pocketbase/pocketbase/core" m "github.com/pocketbase/pocketbase/migrations" ) func init() { m.Register(func(app core.App) error { superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers) if err != nil { return err } record := core.NewRecord(superusers) // note: the values can be eventually loaded via os.Getenv(key) // or from a special local config file record.Set("email", "test@example.com") record.Set("password", "1234567890") return app.Save(record) }, func(app core.App) error { // optional revert operation record, _ := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com") if record == nil { return nil // probably already deleted } return app.Delete(record) }) } ``` -------------------------------- ### Get Collection by ID or Name Source: https://pocketbase.io/docs/api-collections Retrieves a specific collection by its ID or name. Requires authentication. ```APIDOC ## GET /api/collections/`collectionIdOrName` ### Description Retrieves a specific collection by its ID or name. ### Method GET ### Endpoint /api/collections/`collectionIdOrName` ### Parameters #### Path Parameters - **collectionIdOrName** (String) - Required - ID or name of the collection to view. #### Query Parameters - **fields** (String) - Optional - Comma separated string of the fields to return in the JSON response. Ex.: `?fields=*,expand.relField.name` * `:excerpt(maxLength, withEllipsis?)` - Returns a short plain text version of the field string value. Ex.: `?fields=*,description:excerpt(200,true)` ### Request Headers - **Authorization** (String) - Required - TOKEN ### Responses #### Success Response (200) - **id** (String) - The collection ID. - **name** (String) - The collection name. - **type** (String) - The collection type (e.g., 'base', 'auth', 'view'). - **fields** (Array) - An array of field definitions. - **indexes** (Array) - An array of index definitions. - **system** (Boolean) - Indicates if the collection is a system collection. #### Error Responses - **401** - Unauthorized: The request requires valid record authorization token. - **403** - Forbidden: The authorized record is not allowed to perform this action. - **404** - Not Found: The requested resource wasn't found. ``` -------------------------------- ### Get Collection Details Source: https://pocketbase.io/docs/api-collections Retrieves details for a specific collection by its ID or name. Requires authentication. ```javascript const collection = await pb.collections.getOne('demo'); ``` ```dart final collection = await pb.collections.getOne('demo'); ``` -------------------------------- ### Load and Render Templates Source: https://pocketbase.io/docs/go-rendering-templates Loads multiple template files and renders them with provided data. Ensure template files are correctly placed and imported. ```Go import "github.com/pocketbase/pocketbase/tools/template" data := map[string]any{"name": "John"} html, err := template.NewRegistry().LoadFiles( "views/base.html", "views/partial1.html", "views/partial2.html", ).Render(data) ``` -------------------------------- ### Execute Custom Console Command Source: https://pocketbase.io/docs/go-console-commands Build your Go application and execute the custom command. Alternatively, use `go run` for direct execution. ```bash # or "go run main.go hello" ./myapp hello ``` -------------------------------- ### Execute Raw SQL Query (SELECT All) Source: https://pocketbase.io/docs/go-database Use `All()` to populate multiple rows into a slice of structs. The struct definition should match the selected columns. ```go type User struct { Id string `db:"id" json:"id"` Status bool `db:"status" json:"status"` Age int `db:"age" json:"age"` Roles types.JSONArray[string] `db:"roles" json:"roles"` } users := []User{} err := app.DB(). NewQuery("SELECT id, status, age, roles FROM users LIMIT 100"). All(&users) ``` -------------------------------- ### Handle API Errors Source: https://pocketbase.io/docs/api-collections Examples of common API error responses, including unauthorized, forbidden, and not found. ```json { "status": 401, "message": "The request requires valid record authorization token.", "data": {} } ``` ```json { "status": 403, "message": "The authorized record is not allowed to perform this action.", "data": {} } ``` ```json { "status": 404, "message": "The requested resource wasn't found.", "data": {} } ``` -------------------------------- ### GET /api/logs Source: https://pocketbase.io/docs/api-logs Retrieves a paginated list of API logs. Supports filtering, sorting, and field selection. ```APIDOC ## GET /api/logs ### Description Retrieves a paginated list of API logs. Supports filtering, sorting, and field selection. ### Method GET ### Endpoint /api/logs ### Query Parameters - **page** (Number) - Optional - The page (aka. offset) of the paginated list (default to 1). - **perPage** (Number) - Optional - The max returned logs per page (default to 30). - **sort** (String) - Optional - Specify the _ORDER BY_ fields. Add `-` / `+` (default) in front of the attribute for DESC / ASC order, e.g.: `// DESC by the insertion rowid and ASC by level ?sort=-rowid,level`. Supported fields: `@random`, `rowid`, `id`, `created`, `updated`, `level`, `message` and any `data.*` attribute. - **filter** (String) - Optional - Filter expression to filter/search the returned logs list, e.g.: `?filter=(data.url~'test.com' && level>0)`. Supported fields: `id`, `created`, `updated`, `level`, `message` and any `data.*` attribute. The syntax follows `OPERAND OPERATOR OPERAND`. Operators include: `=`, `!=`, `>`, `>=`, `<`, `<=`, `~`, `!~`, `?=`, `?!=`, `?>`, `?>=`, `?<`, `?<=`, `?~`, `?!~`. Parenthesis `(...)`, `&&` (AND) and `||` (OR) can be used for grouping. Single line comments `// Example comment` are supported. Field expressions with array-like values or nested fields from multi-record sources have a **match-all** constraint by default; use `?` prefix for **any/at-least-one-of** constraint (e.g. `multiRelation.title ?= "test"`). - **fields** (String) - Optional - Comma separated string of the fields to return in the JSON response (by default returns all fields). Ex.: `?fields=*,expand.relField.name`. `*` targets all keys at the current depth. Modifiers like `:excerpt(maxLength, withEllipsis?)` are supported. Ex.: `?fields=*,description:excerpt(200,true)` ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **page** (Number) - The current page number. - **perPage** (Number) - The number of items per page. - **totalItems** (Number) - The total number of items available. - **items** (Array) - An array of log objects. - **id** (String) - Log ID. - **created** (String) - Timestamp of log creation. - **data** (Object) - Log specific data. - **message** (String) - Log message. - **level** (Number) - Log level. #### Response Example ```json { "page": 1, "perPage": 20, "totalItems": 2, "items": [ { "id": "ai5z3aoed6809au", "created": "2024-10-27 09:28:19.524Z", "data": { "auth": "_superusers", "execTime": 2.392327, "method": "GET", "referer": "http://localhost:8090/_/", "remoteIP": "127.0.0.1", "status": 200, "type": "request", "url": "/api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", "userIP": "127.0.0.1" }, "message": "GET /api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "level": 0 }, { "id": "26apis4s3sm9yqm", "created": "2024-10-27 09:28:19.524Z", "data": { "auth": "_superusers", "execTime": 2.392327, "method": "GET", "referer": "http://localhost:8090/_/", "remoteIP": "127.0.0.1", "status": 200, "type": "request", "url": "/api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", "userIP": "127.0.0.1" }, "message": "GET /api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "level": 0 } ] } ``` #### Error Responses - **400 Bad Request**: Invalid filter expression. ```json { "status": 400, "message": "Something went wrong while processing your request. Invalid filter.", "data": {} } ``` - **401 Unauthorized**: Missing or invalid authorization token. ```json { "status": 401, "message": "The request requires valid record authorization token.", "data": {} } ``` - **403 Forbidden**: The authorized record is not allowed to perform this action. ```json { "status": 403, "message": "The authorized record is not allowed to perform this action.", "data": {} } ``` ``` -------------------------------- ### Initialize and Authenticate Superuser Client (JavaScript) Source: https://pocketbase.io/docs/how-to-use This snippet shows how to initialize a global PocketBase client for server-side actions, disable auto-cancellation, and authenticate as a superuser using either email/password or an API key. It's recommended for server-side handling where PocketBase acts as a pure data store. ```javascript import PocketBase from "pocketbase" const superuserClient = new PocketBase('https://example.com'); // disable autocancellation so that we can handle async requests from multiple users superuserClient.autoCancellation(false); // option 1: authenticate as superuser using email/password (could be filled with ENV params) await superuserClient.collection('_superusers').authWithPassword(SUPERUSER_EMAIL, SUPERUSER_PASS, { // This will trigger auto refresh or auto reauthentication in case // the token has expired or is going to expire in the next 30 minutes. autoRefreshThreshold: 30 * 60 }) // option 2: OR authenticate as superuser via long-lived "API key" // (see https://pocketbase.io/docs/authentication/#api-keys) superuserClient.authStore.save('YOUR_GENERATED_SUPERUSER_TOKEN') export default superuserClient; ``` -------------------------------- ### GET /api/logs/{id} Source: https://pocketbase.io/docs/api-logs Retrieves a specific API log entry by its ID. Requires authentication with a valid token. ```APIDOC ## GET /api/logs/`id` ### Description Retrieves a specific API log entry by its ID. Requires authentication with a valid token. ### Method GET ### Endpoint /api/logs/`id` ### Headers - **Authorization**: TOKEN - Required - Authentication token. ### Parameters #### Path Parameters - **id** (String) - Required - ID of the log to view. #### Query Parameters - **fields** (String) - Optional - Comma-separated string of the fields to return in the JSON response. Supports modifiers like `:excerpt(maxLength, withEllipsis?)`. ### Responses #### Success Response (200) - **id** (String) - The unique identifier of the log entry. - **created** (String) - The timestamp when the log was created. - **data** (Object) - Contains detailed information about the logged event. - **message** (String) - A message associated with the log entry. - **level** (Number) - The severity level of the log. #### Response Example (200) ```json { "id": "ai5z3aoed6809au", "created": "2024-10-27 09:28:19.524Z", "data": { "auth": "_superusers", "execTime": 2.392327, "method": "GET", "referer": "http://localhost:8090/_/", "remoteIP": "127.0.0.1", "status": 200, "type": "request", "url": "/api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", "userIP": "127.0.0.1" }, "message": "GET /api/collections/_pbc_2287844090/records?page=1&perPage=1&filter=&fields=id", "level": 0 } ``` #### Error Responses - **401**: Unauthorized - The request requires a valid record authorization token. - **403**: Forbidden - The authorized record is not allowed to perform this action. - **404**: Not Found - The requested resource wasn't found. ``` -------------------------------- ### Serve Static Directory Source: https://pocketbase.io/docs/go-routing Use apis.Static() to serve files from a specified directory using an fs.FS instance. The route must include a {path...} wildcard parameter. ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { // serves static files from the provided dir (if exists) se.Router.GET("/{path...}", apis.Static(os.DirFS("/path/to/public"), false)) return se.Next() }) ``` -------------------------------- ### Create Initial Superuser Source: https://pocketbase.io/docs/js-migrations This snippet shows how to create an initial superuser record. It includes a revert operation to delete the superuser if the migration is rolled back. Note that sensitive values like passwords can be loaded from environment variables. ```javascript // pb_migrations/1687801090_initial_superuser.js migrate((app) => { let superusers = app.findCollectionByNameOrId("_superusers") let record = new Record(superusers) // note: the values can be eventually loaded via $os.getenv(key) // or from a special local config file record.set("email", "test@example.com") record.set("password", "1234567890") app.save(record) }, (app) => { // optional revert operation try { let record = app.findAuthRecordByEmail("_superusers", "test@example.com") app.delete(record) } catch { // silent errors (probably already deleted) } }) ```