Vojtěch Struhár

Posted on October 8, 2024 | #astro , #web

thumbnail

Turso on Netlify

I mostly use Astro for my websites, so a backend-ish solution comes in handy from time to time. Today I decided to try out Netlify Functions + Turso database.

Netlify Functions

Getting started with Netlify Functions is definitely a good read.

I’d recommend JavaScript. It’s the most direct option - and I’m not doing anything complicated on the server now.

Basically - all you need to do is create a file at netlify/functions/hello.js in your project. From this file you export a handler function - and your Serverless function is born.

export const handler = async (event) => {
	try {
    return {
      statusCode: 200,
      body: "Hi, mom!"
    };
  } catch (error) {
    return { statusCode: 500, body: error.toString() };
  }
};

Turso database

Creating a Turso database is easy enough. For more detail Netlify-Turso guide, but basically:

Back to Netlify

Turso has a Netlify setup guide. The most important thing (that I overlooked and that’s why I’m writing this article) is to install the Turso extension on Netlify!

Turso extension

Otherwise your function will fail trying to import a libSQL client. Now double check your Netlify functions environment variables and you’re ready to query your database!

import { createClient } from "@libsql/client";

const turso = createClient({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

export const handler = async (event) => {
  try {
    const email = event.queryStringParameters.email;
    validateEmail(email);
    const host = event.headers["host"] || "-";

    await turso.execute({
      sql: "INSERT INTO newsletter (email, domain) VALUES(?, ?);",
      args: [email, host],
    });

    return {
      statusCode: 200,
    };
  } catch (error) {
    return { statusCode: 500, body: error.toString() };
  }
};

/** @param {string} email */
function validateEmail(email) {
  if (email.length > 50) {
    throw new Error("Invalid email");
  }
}

Sidenote: On the free plan of Turso, there are like ~2s cold starts. Oh well. Think of the good price.

Use in Astro

In production, your functions will be deployed at /.netlify/functions/hello. This will not work with traditional astro dev, so I recommend installing the Netlify CLI and developing your project with netlify dev!

If you are using astro in static mode like I am, the best way to get a little interactivity is to just include a script tag and modify the website with plain old JavaScript. It’s almost becoming a lost art these days!

Read next → I added comments to my website!