Astro pages and endpoints that render on demand run on the server, where they
can connect to Upstash Redis with the HTTP-based
@upstash/redis SDK. The same
database can also hold your Astro sessions.
This quickstart uses the Node.js adapter. The code is the same with other server adapters such as Vercel or Netlify.
Database Setup#
Create a Redis database using the Upstash Console
or Upstash CLI. On the database page, open
the Connect section and copy UPSTASH_REDIS_REST_URL and
UPSTASH_REDIS_REST_TOKEN.
Project Setup#
Create an Astro project, add the Node.js adapter and install the SDK:
Put the two values in a .env file at the project root:
Add .env to your .gitignore so the token is not committed.
Redis.fromEnv() and the session driver read these variables from
process.env. During astro dev, Astro exposes .env only to
import.meta.env, so load the file into process.env at the top of
astro.config.mjs:
process.loadEnvFile() keeps variables that are already set, so values from
your host win in production.
Create a Client#
Create src/lib/redis.ts:
Counter Endpoint#
Create src/pages/api/counter.ts. Astro prerenders routes by default, so
prerender = false makes this one run on every request:
You can use the client in a page’s frontmatter too. Create
src/pages/counter.astro:
To render every route on demand instead, set output: "server" in
astro.config.mjs and drop the prerender exports.
Run Locally#
Increment the counter twice, then read it:
Open http://localhost:4321/counter and reload it to see the page views go up.
Sessions#
Astro sessions keep per-visitor data on the server and store only a session ID
in a cookie. To keep that data in Upstash Redis, set the session driver in
astro.config.mjs:
The driver uses @upstash/redis, which you installed above, and reads
UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from process.env at
runtime. Driver options are inlined at build time, so don’t pass the token as
an option.
Read and write session data with Astro.session in a page, or
context.session in an endpoint. Create src/pages/visits.astro:
Reload the page and the number goes up. Each session is one Redis key named after the session ID. The keys have no expiry by default; to let Redis delete idle sessions, pass a TTL in seconds:
Deploy#
Build the app and start the server with the two variables set in the environment:
On a hosting platform, add UPSTASH_REDIS_REST_URL and
UPSTASH_REDIS_REST_TOKEN to the project’s environment variables. The build
does not include them, so the server reads them when it starts.
Next Steps#
- Add rate limiting to an endpoint with @upstash/ratelimit.
- Run durable background jobs from Astro with Upstash Workflow.