Cloudflare Docs
Workers
Edit this page
Give us feedback
Set theme to dark (⇧+D)

PlanetScale

PlanetScale is a MySQL-compatible platform that makes databases infinitely scalable, easier and safer to manage.

Database Integrations allow you to connect to a database from your Worker by getting the right configuration from your database provider and adding it as secrets to your Worker.

​​ Set up an integration with PlanetScale

To set up an integration with PlanetScale:

  1. You need to have an existing PlanetScale database to connect to. Create a PlanetScale database or import an existing database to PlanetScale.

  2. From the PlanetScale web console, create a products table with the following query:

    CREATE TABLE products (
    id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name varchar(255) NOT NULL,
    image_url varchar(255),
    category_id INT,
    KEY category_id_idx (category_id)
    );
  3. Insert some data in your newly created table. Run the following command to add a product and category to your table:

    INSERT INTO products (name, image_url, category_id)
    VALUES ('Ballpoint pen', 'https://example.com/500x500', '1');
  4. Add the PlanetScale integration to your Worker:

    1. Log in to the Cloudflare dashboard and select your account.
    2. In Account Home, select Workers & Pages.
    3. In Overview, select your Worker.
    4. Select Integrations > PlanetScale.
    5. Follow the setup flow, selecting the database created in step 1.
  5. In your Worker, install the @planetscale/database driver to connect to your PlanetScale database and start manipulating data:

    npm install @planetscale/database
  6. The following example shows how to make a query to your PlanetScale database in a Worker. The credentials needed to connect to PlanetScale have been automatically added as secrets to your Worker through the integration.

    import { connect } from '@planetscale/database';
    export default {
    async fetch(request, env) {
    const config = {
    host: env.DATABASE_HOST,
    username: env.DATABASE_USERNAME,
    password: env.DATABASE_PASSWORD,
    // see https://github.com/cloudflare/workerd/issues/698
    fetch: (url, init) => {
    delete (init)["cache"];
    return fetch(url, init);
    }
    }
    const conn = connect(config)
    const data = await conn.execute('SELECT * FROM products;')
    return new Response(JSON.stringify(data.rows), {
    status: 200,
    headers: {
    'Content-Type': 'application/json'
    }
    });
    },
    };

To learn more about PlanetScale, refer to PlanetScale’s official documentation.