### Basic `scloud launch` command Source: https://docs.serverpod.dev/cloud/reference/cli/commands/launch Initiates an interactive guided setup for a new Serverpod Cloud project. Prompts for necessary settings and confirms actions before execution. ```bash scloud launch ``` -------------------------------- ### Launch Serverpod Project on Serverpod Cloud Source: https://docs.serverpod.dev/cloud/getting-started/launch Run the interactive launch command to guide through initial setup and deployment. This command handles project creation, environment configuration, and building/deploying your server. ```bash scloud launch ``` -------------------------------- ### Start the Serverpod Mini server Source: https://docs.serverpod.dev/serverpod-mini Run the main Dart file to start your Serverpod Mini server. ```bash $ dart bin/main.dart ``` -------------------------------- ### Start Pixorama Server Source: https://docs.serverpod.dev/tutorials/tutorials/real-time-communication Navigate to the pixorama_server directory and run this command to start the server. ```bash dart bin/main.dart ``` -------------------------------- ### Deployment list output example Source: https://docs.serverpod.dev/cloud/reference/deployment/deploying-your-application Example output for `scloud deployment list`, showing deployment history with status and timestamps. ```text # | Project | Deploy Id | Status | Started | Finished | Info --+---------+--------------------------------------+---------+---------------------+---------------------+---------------------------------- 0 | my-app | 3bbb0189-784b-4b9b-a3d9-c84f4c787f54 | FAILURE | 2025-03-28 13:42:38 | 2025-03-28 13:43:33 | User build FAILURE - see build log 1 | my-app | 4a60a5ec-067c-4c76-8ecd-30a6410c1dc2 | SUCCESS | 2025-03-27 15:24:57 | 2025-03-27 15:27:50 | 2 | my-app | 73e66b41-64fc-4920-b6ef-4918cc6ceca1 | FAILURE | 2025-03-27 15:19:37 | 2025-03-27 15:20:34 | User build FAILURE - see build log 3 | my-app | 4bb1e636-3ec8-4f78-b294-32c80efd513a | SUCCESS | 2025-03-27 10:12:36 | 2025-03-27 10:19:48 | ``` -------------------------------- ### Start the Serverpod Server Source: https://docs.serverpod.dev/get-started/models-and-data Navigate to the server directory, start the Docker services, and run the Dart application. ```bash $ cd magic_recipe_server $ docker compose up -d $ dart bin/main.dart ``` -------------------------------- ### Start Database and Apply Migrations Source: https://docs.serverpod.dev/get-started/working-with-the-database Run these commands in your server directory to start the database using Docker Compose and apply any pending database migrations. ```bash $ cd magic_recipe_server $ docker compose up -d # Start the database container $ dart bin/main.dart --apply-migrations # Apply any pending migrations ``` -------------------------------- ### Install Serverpod Cloud CLI Source: https://docs.serverpod.dev/cloud/reference/cli/introduction Run this command to install the Serverpod Cloud CLI globally on your system. ```bash dart pub global activate serverpod_cloud_cli ``` -------------------------------- ### Install Carapace on Windows Source: https://docs.serverpod.dev/tools/shell-completion Use winget to install Carapace on Windows. ```bash winget install carapace ``` -------------------------------- ### Start Serverpod Server Source: https://docs.serverpod.dev/get-started Commands to start the Serverpod server and apply database migrations. Ensure no other Serverpod servers or Docker containers are running to avoid port conflicts. ```bash cd magic_recipe_server docker compose up -d dart bin/main.dart --apply-migrations ``` -------------------------------- ### Complete example: Endpoint to load config Source: https://docs.serverpod.dev/cloud/reference/deployment/assets A full example of a Serverpod endpoint that loads and returns application configuration from a JSON asset file. ```dart import 'dart:io'; import 'dart:convert'; import 'package:serverpod/serverpod.dart'; class ConfigEndpoint extends Endpoint { Future> getConfig(Session session) async { try { final file = File('./assets/config/app_config.json'); if (!await file.exists()) { throw Exception('Config file not found'); } final contents = await file.readAsString(); final config = jsonDecode(contents) as Map; return config; } catch (e) { throw Exception('Failed to load config: $e'); } } } ``` -------------------------------- ### Install Serverpod completion spec for Carapace Source: https://docs.serverpod.dev/tools/shell-completion Install the completion specification for Serverpod using Carapace. ```bash serverpod completion install --tool carapace ``` -------------------------------- ### Run Server with Database Migrations Source: https://docs.serverpod.dev/ Start the Serverpod server and apply initial database migrations. This command should be run from the server directory. ```bash cd my_project/my_project_server $ dart run bin/main.dart --apply-migrations ``` -------------------------------- ### Start PostgreSQL Database with Docker Source: https://docs.serverpod.dev/ Navigate to the server directory and run this command to start the PostgreSQL database using Docker Compose. Press Ctrl+C to stop. ```bash cd my_project/my_project_server $ docker compose up ``` -------------------------------- ### Start Serverpod LSP Server Source: https://docs.serverpod.dev/tools/lsp Use this command to start the Serverpod LSP server. This server provides diagnostics for YAML protocol files. ```bash serverpod language-server ``` -------------------------------- ### Start Development Database with Docker Compose Source: https://docs.serverpod.dev/concepts/database/connection Use `docker compose up --build --detach` from the `server` package root to start the preconfigured PostgreSQL database instance for development. ```bash $ docker compose up --build --detach ``` -------------------------------- ### Install Carapace on Ubuntu/Debian Source: https://docs.serverpod.dev/tools/shell-completion Use apt to install Carapace on Ubuntu or Debian-based systems. ```bash sudo apt install carapace-bin ``` -------------------------------- ### Verify Serverpod CLI Installation Source: https://docs.serverpod.dev/ Confirm that the Serverpod CLI has been installed correctly by running the 'serverpod' command. This should display the command's help information. ```bash $ serverpod ``` -------------------------------- ### Install Bash Completion with Completely Source: https://docs.serverpod.dev/cloud/reference/cli/commands/completion Run this command to install bash completion scripts using the Completely tool. The script is saved to a location where bash automatically picks it up. ```bash scloud completion install -t completely ``` -------------------------------- ### Check Docker Installation Source: https://docs.serverpod.dev/ Verify your Docker installation by running the 'docker info' command. Ensure Docker is running, especially if using Docker Desktop, to manage PostgreSQL locally. ```bash $ docker info ``` -------------------------------- ### scloud Completion Install Command Usage Source: https://docs.serverpod.dev/cloud/reference/cli/commands/completion This displays the usage for the `install` subcommand of `scloud completion`, outlining options for specifying the completion tool, executable name, and write directory. ```bash Install a command line completion script Usage: scloud completion install [arguments] -h, --help Print this usage information. -t, --tool (mandatory) The completion tool to target [completely] Use the `completely` tool (https://github.com/bashly-framework/completely) [carapace] Use the `carapace` tool (https://carapace.sh/) -e, --exec-name Override the name of the executable -d, --write-dir Override the directory to write the script to Run "scloud help" to see global options. ``` -------------------------------- ### Install Serverpod Cloud CLI Source: https://docs.serverpod.dev/cloud/getting-started/installation Installs the `serverpod_cloud_cli` package globally using Dart. This makes the `scloud` command available in your terminal. ```bash dart pub global activate serverpod_cloud_cli ``` -------------------------------- ### Start Docker Compose for Testing Source: https://docs.serverpod.dev/concepts/testing/get-started Ensure your Postgres and Redis instances are running by executing this command before running your tests. ```bash docker compose up --build --detach ``` -------------------------------- ### Create a new Serverpod Mini project Source: https://docs.serverpod.dev/serverpod-mini Use this command to initialize a new Serverpod project with the Mini configuration. ```bash $ serverpod create myminipod --mini ``` -------------------------------- ### Run a Defined Script Source: https://docs.serverpod.dev/tools/run-scripts Execute a script defined in your `pubspec.yaml` by prefixing its name with `serverpod run`. For example, to run the `start` script, use `$ serverpod run start`. ```bash $ serverpod run start ``` -------------------------------- ### Use Custom EmailSignInWidget with SignInWidget Source: https://docs.serverpod.dev/concepts/authentication/providers/email/customizing-the-ui Supply a custom `EmailSignInWidget` to the `SignInWidget` to override the default behavior. This example starts the flow with the registration screen. ```dart SignInWidget( client: client, emailSignInWidget: EmailSignInWidget( client: client, // Change the initial screen to start registration startScreen: EmailFlowScreen.startRegistration, ), ) ``` -------------------------------- ### Syntax and examples for .scloudignore Source: https://docs.serverpod.dev/cloud/reference/deployment/deploying-your-application Define patterns in `.scloudignore` to control which files are included in your deployment package. Supports comments and overriding `.gitignore` rules. ```ignore # Comments start with a hash /specific_file.txt # Exclude a specific file *.log # Exclude all log files /large_dir/ # Exclude a directory and its contents # Override .gitignore rules !lib/src/generated/ # Include all generated code, even if ignored by .gitignore ``` -------------------------------- ### Run Flutter Application Source: https://docs.serverpod.dev/ Navigate to the Flutter app directory and run this command to start the Flutter application in your browser. ```bash cd my_project/my_project_flutter $ flutter run -d chrome ``` -------------------------------- ### Filter included lists Source: https://docs.serverpod.dev/concepts/database/relation-queries Use the `where` clause within `includeList` to filter the related objects based on specified conditions. This example retrieves employees whose names start with 'a'. ```dart var user = await Company.db.findById( session, employeeId, include: Company.include( employees: Employee.includeList( where: (t) => t.name.ilike('a%') ), ), ); ``` -------------------------------- ### Paginate included lists Source: https://docs.serverpod.dev/concepts/database/relation-queries Use `limit` and `offset` within `includeList` to paginate the results of a related list. This example retrieves the next 10 employees starting from the 11th record. ```dart var user = await Company.db.findById( session, employeeId, include: Company.include( employees: Employee.includeList( limit: 10, offset: 10, ), ), ); ``` -------------------------------- ### GitHub CI Workflow Example Source: https://docs.serverpod.dev/cloud/reference/personal-access-tokens Automate Serverpod Cloud deployments in a GitHub Actions workflow by storing the token as a secret and exposing it as `SERVERPOD_CLOUD_TOKEN`. ```yaml name: Automated Serverpod Cloud deploy on: push: branches: [main] permissions: contents: read jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Flutter SDK uses: subosito/flutter-action@v2 - name: Activate serverpod command run: dart pub global activate serverpod_cli - uses: serverpod/serverpod-cloud-deploy@v1 with: token: ${{ secrets.MY_SERVERPOD_CLOUD_ACCESS_TOKEN }} ``` -------------------------------- ### Start Server in Serverless Role Source: https://docs.serverpod.dev/deployments/general Launch the Serverpod server with the 'serverless' role. This configuration is suitable for serverless environments where the server only handles incoming connections. ```bash $ dart bin/main.dart --role serverless ``` -------------------------------- ### Filter HTTP Methods for a Route Source: https://docs.serverpod.dev/concepts/webserver/routing Specify the allowed HTTP methods for a route using the 'methods' parameter in the Route constructor. This example defines a route that responds to GET, POST, and DELETE requests. ```dart class UserRoute extends Route { UserRoute() : super( methods: {Method.get, Method.post, Method.delete}, ); // ... } ``` -------------------------------- ### Apply database migrations Source: https://docs.serverpod.dev/concepts/authentication/legacy/setup Apply the pending database migrations, including those for the auth module, by starting your server with the '--apply-migrations' flag. ```bash $ dart run bin/main.dart --role maintenance --apply-migrations ``` -------------------------------- ### Upgrade Serverpod Mini Project Source: https://docs.serverpod.dev/upgrading/upgrade-from-mini Run this command in your server directory to add configuration files for the full Serverpod version. Ensure you have backed up your project first. ```bash serverpod create . ``` -------------------------------- ### Define a Custom API Route Source: https://docs.serverpod.dev/concepts/webserver/routing Extend the Route class to create custom handlers for specific API endpoints. Implement handleCall to process requests and return responses. This example handles GET and POST requests. ```dart class ApiRoute extends Route { ApiRoute() : super(methods: {Method.get, Method.post}); @override Future handleCall(Session session, Request request) async { if (request.method == Method.post) { final body = await request.readAsString(); final data = jsonDecode(body); return Response.ok( body: Body.fromString( jsonEncode({'status': 'success', 'data': data}), mimeType: MimeType.json, ), ); } return Response.ok( body: Body.fromString( jsonEncode({'message': 'Hello from API'}), mimeType: MimeType.json, ), ); } } ``` -------------------------------- ### Verify CLI Installation Source: https://docs.serverpod.dev/cloud/getting-started/installation Checks if the `scloud` command is installed and accessible. It should print the currently installed version of the CLI. ```bash scloud version ``` -------------------------------- ### Example Migration File Structure Source: https://docs.serverpod.dev/concepts/database/migrations A migration file created with a tag will include the tag in its name, following the timestamp. This aids in organizing and identifying migrations. ```bash ├── migrations │ └── 20231205080937028-v1-0-0 ``` -------------------------------- ### Check Flutter Installation Source: https://docs.serverpod.dev/ Verify your Flutter installation by running the 'flutter doctor' command in your terminal. This ensures Flutter is set up correctly before proceeding with Serverpod installation. ```bash $ flutter doctor ``` -------------------------------- ### Preview deployment files Source: https://docs.serverpod.dev/cloud/reference/cli/commands/deploy Use the `--show-files` flag to preview the file tree that will be uploaded during deployment. This helps verify that your ignore files are working correctly. ```bash $ scloud deploy --show-files ``` -------------------------------- ### Show deployment progress Source: https://docs.serverpod.dev/cloud/reference/cli/commands/deploy Use this command to follow the progress of a deployment. ```bash scloud deployment show ``` -------------------------------- ### Navigate to Serverpod Mini server directory Source: https://docs.serverpod.dev/serverpod-mini Change into the server directory of your newly created Serverpod Mini project. ```bash $ cd myminipod/myminipod_server ``` -------------------------------- ### Prepare Deployment Script Source: https://docs.serverpod.dev/deployments/deploying-to-gcr-console Copy the deployment script to your server directory and make it executable before configuring and running it. ```bash cp deploy/gcp/console_gcr/cloud-run-deploy.sh . chmod u+x cloud-run-deploy.sh ``` -------------------------------- ### Deployment CLI Usage Source: https://docs.serverpod.dev/cloud/reference/cli/commands/deployment This is the main entry point for deployment-related commands. Use subcommands to perform specific actions. ```bash scloud deployment [arguments] ``` -------------------------------- ### Launch command with arguments Source: https://docs.serverpod.dev/cloud/reference/cli/commands/launch Provides options to specify plan, database enablement, deployment, Dart version, and project ID for the Serverpod Cloud project launch. ```bash scloud launch --plan=starter --enable-db --deploy --dart-version=3.2.0 --project=my_project_id ``` -------------------------------- ### Install Firebase CLI and FlutterFire CLI Source: https://docs.serverpod.dev/concepts/authentication/providers/firebase/setup Install the Firebase CLI and FlutterFire CLI globally using npm and Dart. ```bash npm install -g firebase-tools dart pub global activate flutterfire_cli ``` -------------------------------- ### Install Carapace Tool on macOS Source: https://docs.serverpod.dev/cloud/reference/cli/commands/completion Prerequisite for enabling Carapace completion. Install the Carapace tool using Homebrew on macOS. ```bash brew install carapace ``` -------------------------------- ### Start database container Source: https://docs.serverpod.dev/concepts/authentication/legacy/setup Ensure your database container is running with the necessary configurations by executing 'docker compose up --build --detach' from your server project directory. ```bash $ docker compose up --build --detach ``` -------------------------------- ### Check Server Startup Completion Source: https://docs.serverpod.dev/concepts/health-checks Use the /startupz endpoint to verify if the server has finished initializing, including migrations. Kubernetes waits for this to pass before starting liveness/readiness probes. ```bash curl http://localhost:8080/startupz # Returns: 200 OK once startup is complete ``` -------------------------------- ### Launch command for a new project Source: https://docs.serverpod.dev/cloud/reference/cli/commands/launch Launches a new Serverpod Cloud project with specified settings, including creating a new project ID. ```bash scloud launch --new-project=my_new_project_id --plan=growth --no-enable-db ``` -------------------------------- ### Create a new Serverpod project Source: https://docs.serverpod.dev/get-started Use the `serverpod create` command to generate a new project structure including server, client, and Flutter app. ```bash serverpod create magic_recipe ``` -------------------------------- ### Full example with SetNull on update and NoAction on delete Source: https://docs.serverpod.dev/concepts/database/relations/referential-actions This example demonstrates setting `parentId` to null if the parent is updated, and taking no action if the parent is deleted. ```dart class: Example table: example fields: parentId: int?, relation(parent=example, onUpdate=SetNull, onDelete=NoAction) ``` -------------------------------- ### Get Database Connection Details Source: https://docs.serverpod.dev/cloud/guides/database Run this command from your server project directory to get the host, port, and database name for your Serverpod Cloud database. ```bash scloud db connection ``` -------------------------------- ### Apply Migrations with Server Runtime Source: https://docs.serverpod.dev/concepts/database/migrations Apply migrations by running the server with the --apply-migrations flag. Migrations are applied during startup and ensured to run only once. ```bash $ dart run bin/main.dart --apply-migrations ``` -------------------------------- ### Install Serverpod CLI Source: https://docs.serverpod.dev/ Install the Serverpod command-line interface (CLI) globally using the Dart package manager. This tool is essential for managing Serverpod projects. ```bash $ dart pub global activate serverpod_cli ``` -------------------------------- ### Initialize Terraform Configuration Source: https://docs.serverpod.dev/deployments/deploying-to-gce-terraform Run this command to download the Serverpod module and initialize your Terraform configuration. This is a necessary first step before applying any infrastructure changes. ```bash $ terraform init ``` -------------------------------- ### Middleware Execution Order Example Source: https://docs.serverpod.dev/concepts/webserver/middleware Demonstrates how middleware is applied based on path hierarchy and registration order. More specific paths take precedence, and within the same path, middleware executes in the order it was registered. ```dart pod.webServer.addMiddleware(rateLimitMiddleware, '/api/users'); // Executes last for /api (inner) pod.webServer.addMiddleware(apiKeyMiddleware, '/api'); // Executes first for /api (outer) ``` -------------------------------- ### Initiate Recurring Task on Server Start Source: https://docs.serverpod.dev/concepts/scheduling/recurring-task Schedule the initial future call with a delay when the server starts. This ensures the recurring task begins its execution cycle. ```dart import 'package:serverpod/serverpod.dart'; import 'package:serverpod_auth_idp_server/core.dart'; import 'src/generated/protocol.dart'; import 'src/generated/endpoints.dart'; void run(List args) async { final pod = Serverpod( args, Protocol(), Endpoints(), ); await pod.start(); await pod.futureCalls.callWithDelay(Duration(minutes: 20)).example.doWork(2); } ``` -------------------------------- ### Initialize SessionManager and Client Source: https://docs.serverpod.dev/concepts/authentication/legacy/setup Set up the `SessionManager` and `Client` in your `main` function. This involves configuring the client to connect to your Serverpod, handling IP addresses for different environments (emulator vs. real device), and initializing the session manager. ```dart late SessionManager sessionManager; late Client client; void main() async { // Need to call this as we are using Flutter bindings before runApp is called. WidgetsFlutterBinding.ensureInitialized(); // The android emulator does not have access to the localhost of the machine. // const ipAddress = '10.0.2.2'; // Android emulator ip for the host // On a real device replace the ipAddress with the IP address of your computer. const ipAddress = 'localhost'; // Sets up a singleton client object that can be used to talk to the server from // anywhere in our app. The client is generated from your server code. // The client is set up to connect to a Serverpod running on a local server on // the default port. You will need to modify this to connect to staging or // production servers. client = Client( 'http://$ipAddress:8080/', authenticationKeyManager: FlutterAuthenticationKeyManager(), )..connectivityMonitor = FlutterConnectivityMonitor(); // The session manager keeps track of the signed-in state of the user. You // can query it to see if the user is currently signed in and get information // about the user. sessionManager = SessionManager( caller: client.modules.auth, ); await sessionManager.initialize(); runApp(MyApp()); } ``` -------------------------------- ### Configure Main Application Widget Source: https://docs.serverpod.dev/tutorials/tutorials/real-time-communication Sets up the main entry point for the Flutter application, initializing the Serverpod client and defining the root widget. ```dart // lib/main.dart import 'package:pixorama_client/pixorama_client.dart'; import 'package:flutter/material.dart'; import 'package:serverpod_flutter/serverpod_flutter.dart'; import 'src/pixorama.dart'; var client = Client('http://$localhost:8080/') ..connectivityMonitor = FlutterConnectivityMonitor(); void main() { // Start the app. runApp(const PixoramaApp()); } class PixoramaApp extends StatelessWidget { const PixoramaApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Pixorama', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( body: const Pixorama(), ), ); } } ``` -------------------------------- ### Dry run with file preview Source: https://docs.serverpod.dev/cloud/reference/cli/commands/deploy Combine `--dry-run` and `--show-files` to preview the file tree without actually deploying. This is useful for verifying deployment contents. ```bash $ scloud deploy --dry-run --show-files ``` -------------------------------- ### Install Firebase CLI and Configure Flutterfire Source: https://docs.serverpod.dev/concepts/authentication/legacy/providers/firebase Install the necessary Firebase CLI tools and configure your Flutter project with Flutterfire. This is a prerequisite for using Firebase services in your Flutter app. ```bash $ flutter pub add firebase_core firebase_auth firebase_ui_auth $ flutterfire configure ``` -------------------------------- ### Initialize gcloud CLI Source: https://docs.serverpod.dev/deployments/deploying-to-gcr-console Run this command to initialize the Google Cloud CLI tools and authenticate with your Google Cloud account. ```bash $ gcloud init ``` -------------------------------- ### Initial Request for Static File Source: https://docs.serverpod.dev/concepts/webserver/static-files Demonstrates an initial HTTP GET request for a static file, showing the expected 200 OK response with ETag and Last-Modified headers for caching. ```http GET /static/logo.png HTTP/1.1 Host: example.com HTTP/1.1 200 OK ETag: "abc123" Last-Modified: Tue, 15 Nov 2024 12:00:00 GMT Content-Length: 12345 [file content] ``` -------------------------------- ### Start Server in Production Mode with Specific ID Source: https://docs.serverpod.dev/deployments/general Use this command to start the Serverpod server in production mode with a specific server ID. This is useful when running multiple servers in a cluster. ```bash $ dart bin/main.dart --mode production --server-id 2 ``` -------------------------------- ### Display scloud help information Source: https://docs.serverpod.dev/cloud/reference/cli/commands/help Run this command to see global options and general usage for the scloud CLI. Use `scloud help [command]` for specific command details. ```bash scloud help [command] ``` -------------------------------- ### Create a Serverpod Cloud project Source: https://docs.serverpod.dev/cloud/reference/cli/commands/project Use this command to create a new Serverpod Cloud project. You can specify whether to enable the database for the project. ```bash scloud project create my-project --enable-db ``` ```bash scloud project create my-project --no-enable-db ``` -------------------------------- ### Upgrade Dart SDK in Install Dependencies Script Source: https://docs.serverpod.dev/deployments/deploying-to-aws This script block is for users with Serverpod CLI version <= 2.0.2. It installs a specified Dart SDK version if not present and sets it as the default, ensuring compatibility. ```bash #!/bin/bash #### COPY THE CODE FROM HERE DART_VERSION=3.5.1 # Uncomment the following code if you have already generated the project with the older version of serverpod cli # What this code do is to remove our previous way of setting dart version in the launch template if [ -f "/etc/profile.d/script.sh" ]; then sudo rm /etc/profile.d/script.sh fi ## install specified dart version if it is not present on the machine if [ ! -d "/usr/lib/dart$DART_VERSION" ]; then wget -q https://storage.googleapis.com/dart-archive/channels/stable/release/$DART_VERSION/sdk/dartsdk-linux-x64-release.zip -P /tmp cd /tmp || exit unzip -q dartsdk-linux-x64-release.zip sudo mv dart-sdk/ /usr/lib/dart$DART_VERSION/ sudo chmod -R 755 /usr/lib/dart$DART_VERSION/ rm -rf dartsdk-linux-x64-release.zip fi ## make symlink to use this dart as default sudo ln -sf "/usr/lib/dart$DART_VERSION/bin/dart" /usr/local/bin/dart #### STOP COPYING THE CODE FROM HERE #### THE FOLLOWING SHOULD BE THE SAME AS THE PREVIOUS CODE cat > /lib/systemd/system/serverpod.service << EOF [Unit] Description=Serverpod server After=multi-user.target [Service] User=ec2-user WorkingDirectory=/home/ec2-user ExecStart=/home/ec2-user/serverpod/active/mypod_server/deploy/aws/scripts/run_serverpod Restart=always [Install] WantedBy=multi-user.target WantedBy=network-online.target EOF systemctl daemon-reload ``` -------------------------------- ### Create and Apply Database Migrations Source: https://docs.serverpod.dev/concepts/modules After adding a module, create a new database migration and apply it using `serverpod create-migration` and `dart bin/main.dart --apply-migrations`. ```bash $ serverpod create-migration $ dart bin/main.dart --apply-migrations ``` -------------------------------- ### Passwords File Example (YAML) Source: https://docs.serverpod.dev/concepts/configuration Example `secrets.yaml` file for storing sensitive information. It includes a shared section for secrets used across all run modes and specific sections for development and production environments. ```yaml shared: myCustomSharedSecret: 'secret_key' development: database: 'development_password' redis: 'development_password' serviceSecret: 'development_service_secret' twilioApiKey: 'dev_twilio_key' production: database: 'production_password' redis: 'production_password' serviceSecret: 'production_service_secret' twilioApiKey: 'prod_twilio_key' ``` -------------------------------- ### Verify Serverpod CLI Version Source: https://docs.serverpod.dev/upgrading/archive/upgrade-to-one-point-two Check your installed Serverpod CLI version after updating. ```bash serverpod version ``` -------------------------------- ### Enable all experimental features Source: https://docs.serverpod.dev/concepts/experimental Use the `--experimental-features=all` flag with the `serverpod generate` command to enable all available experimental features. ```bash serverpod generate --experimental-features=all ``` -------------------------------- ### Run Flutter App Source: https://docs.serverpod.dev/get-started Command to start the Flutter application, typically in a web browser. ```bash cd magic_recipe_flutter flutter run -d chrome ``` -------------------------------- ### Deploy Serverpod project Source: https://docs.serverpod.dev/cloud/reference/cli/commands/deploy Deploys your Serverpod project to the cloud. This is the basic command to initiate a deployment. ```bash $ scloud deploy ``` -------------------------------- ### Verbose deployment logging Source: https://docs.serverpod.dev/cloud/reference/deployment/deploying-your-application Get detailed information during deployment, especially useful for troubleshooting errors. ```bash scloud deploy --verbose ``` -------------------------------- ### OR logical operator Source: https://docs.serverpod.dev/concepts/database/filter Chain conditions with the `|` operator for OR logic. Fetches users whose names start with 'A' or 'B'. ```dart await User.db.find( session, where: (t) => (t.name.like('A%') | t.name.like('B%')) ); ``` -------------------------------- ### Sending Messages to a Server Stream Source: https://docs.serverpod.dev/concepts/streams Provides an example of how a client can send a message to a server-side stream endpoint. ```dart client.myEndpoint.sendStreamMessage(MyMessage(text: 'Hello')); ``` -------------------------------- ### Create a New Serverpod Project Source: https://docs.serverpod.dev/ Use this command to initialize a new Serverpod project. The project name must be a valid Dart package name (lowercase, numbers, underscores). ```bash $ serverpod create my_project ``` -------------------------------- ### Add GCP Cloud Storage Package Source: https://docs.serverpod.dev/concepts/file-uploads Install the GCP cloud storage package using Dart pub. ```bash $ dart pub add serverpod_cloud_storage_gcp ``` -------------------------------- ### Configure Google Sign-In with Environment Variables Source: https://docs.serverpod.dev/concepts/authentication/providers/google/configuration Use the `--dart-define` option to pass client IDs during build time. The provider automatically uses `GOOGLE_CLIENT_ID` and `GOOGLE_SERVER_CLIENT_ID` if not provided during initialization. This method is ideal for managing separate credentials for different platforms and build environments without committing them to version control. ```bash flutter run \ -d "" \ --dart-define="GOOGLE_CLIENT_ID=.apps.googleusercontent.com" \ --dart-define="GOOGLE_SERVER_CLIENT_ID=.apps.googleusercontent.com" ``` -------------------------------- ### Add Facebook Auth Package to Flutter Project Source: https://docs.serverpod.dev/concepts/authentication/providers/facebook/setup Install the necessary package for Facebook authentication in your Flutter project. ```bash flutter pub add serverpod_auth_idp_flutter_facebook ``` -------------------------------- ### Create test.yaml configuration file Source: https://docs.serverpod.dev/concepts/testing/get-started Set up the `test.yaml` file in the `config` directory for your test environment. This file configures ports to be available dynamically and specifies database connection details. ```yaml # This is the configuration file for your test environment. # All ports are set to zero in this file which makes the server find the next available port. # This is needed to enable running tests concurrently. To set up your server, you will # need to add the name of the database you are connecting to and the user name. # The password for the database is stored in the config/passwords.yaml. # Configuration for the main API test server. apiServer: port: 0 publicHost: localhost publicPort: 0 publicScheme: http # Configuration for the Insights test server. insightsServer: port: 0 publicHost: localhost publicPort: 0 publicScheme: http # Configuration for the web test server. webServer: port: 0 publicHost: localhost publicPort: 0 publicScheme: http # This is the database setup for your test server. database: host: localhost port: 9090 name: _test user: postgres ``` -------------------------------- ### Case-insensitive LIKE filter Source: https://docs.serverpod.dev/concepts/database/filter Use `ilike` for case-insensitive string matching. Fetches users whose names start with 'a' or 'A'. ```dart await User.db.find( session, where: (t) => t.name.ilike('a%') ); ``` -------------------------------- ### Development Configuration (YAML) Source: https://docs.serverpod.dev/concepts/configuration Example `development.yaml` for server configuration, including API, insights, web server, database, and Redis settings. This file is used when running the server in development mode. ```yaml apiServer: port: 8080 publicHost: localhost publicPort: 8080 publicScheme: http websocketPingInterval: 30 insightsServer: port: 8081 publicHost: localhost publicPort: 8081 publicScheme: http webServer: port: 8082 publicHost: localhost publicPort: 8082 publicScheme: http database: host: localhost port: 8090 name: database_name user: postgres maxConnectionCount: 10 redis: enabled: false host: localhost port: 8091 maxRequestSize: 524288 sessionLogs: persistentEnabled: true cleanupInterval: 24h retentionPeriod: 90d retentionCount: 100000 consoleEnabled: true consoleLogFormat: json futureCallExecutionEnabled: true futureCall: concurrencyLimit: 5 scanInterval: 2000 ``` -------------------------------- ### Filter by String Like Pattern Source: https://docs.serverpod.dev/concepts/database/filter Fetch all users whose name starts with 'A' using a case-sensitive like match. ```dart await User.db.find( session, where: (t) => t.name.like('A%') ); ``` -------------------------------- ### Navigate to Serverpod Project Directory Source: https://docs.serverpod.dev/cloud/getting-started/launch Before deploying, navigate to the root directory of your Serverpod project using your terminal. ```bash cd your_serverpod_project ``` -------------------------------- ### Delete Expired Account Requests Source: https://docs.serverpod.dev/concepts/authentication/providers/email/admin-operations Deletes all expired account requests, which are typically from users who started but did not complete registration. ```APIDOC ## Cleanup Operations ### Cleaning Up Expired Account Requests Account requests that have expired (users who started registration but never completed it) should be cleaned up: ```dart // Delete all expired account requests await admin.deleteExpiredAccountRequests(session); ``` ``` -------------------------------- ### Configure Microsoft Sign-In with Environment Variables Source: https://docs.serverpod.dev/concepts/authentication/providers/microsoft/configuration Use `--dart-define` to pass Microsoft client configuration during build time. This is useful for managing different credentials per platform or build environment. ```bash flutter run -d \ --dart-define="MICROSOFT_CLIENT_ID=your_client_id" \ --dart-define="MICROSOFT_REDIRECT_URI=msauth://auth" \ --dart-define="MICROSOFT_TENANT=common" ``` -------------------------------- ### Complex Pre-deploy Workflow with Multiple Steps Source: https://docs.serverpod.dev/cloud/reference/deployment/deployment-hooks Execute a series of preparation steps, including code generation and building, within a single pre-deploy hook. ```yaml project: projectId: my-project scripts: pre_deploy: - echo "Starting deployment preparation..." - serverpod generate - serverpod run flutter_build - echo "Preparation complete" ``` -------------------------------- ### Flutter App Setup with AuthSessionManager Source: https://docs.serverpod.dev/concepts/authentication/setup Initialize the Serverpod client in your Flutter app, integrating `FlutterConnectivityMonitor` and `FlutterAuthSessionManager` for authentication. ```dart import 'package:flutter/material.dart'; import 'package:serverpod_flutter/serverpod_flutter.dart'; import 'package:serverpod_auth_idp_flutter/serverpod_auth_idp_flutter.dart'; import 'package:your_client/your_client.dart'; late Client client; void main() async { WidgetsFlutterBinding.ensureInitialized(); const serverUrl = 'http://localhost:8080/'; // Create the client with the auth session manager client = Client(serverUrl) ..connectivityMonitor = FlutterConnectivityMonitor() ..authSessionManager = FlutterAuthSessionManager(); // Initialize authentication (restores session from storage and validates) await client.auth.initialize(); runApp(MyApp()); } ``` -------------------------------- ### Add Serverpod Auth Firebase Flutter Package Source: https://docs.serverpod.dev/concepts/authentication/legacy/providers/firebase Install the serverpod_auth_firebase_flutter package to integrate Firebase authentication with your Serverpod client. ```bash $ flutter pub add serverpod_auth_firebase_flutter ``` -------------------------------- ### Filter by String Not Like Pattern Source: https://docs.serverpod.dev/concepts/database/filter Fetch all users whose name does not start with 'B' using a case-sensitive not like match. ```dart await User.db.find( session, where: (t) => t.name.notLike('B%') ); ```