Express Integration

This guide will show you how to integrate Better Query with express.js.

Before you start, make sure you have a Better Query instance configured. If you haven't done that yet, check out the installation.

Note that CommonJS (cjs) isn't supported. Use ECMAScript Modules (ESM) by setting "type": "module" in your package.json or configuring your tsconfig.json to use ES modules.

Mount the handler

To enable Better Query to handle requests, we need to mount the handler to an API route. Create a catch-all route to manage all requests to /api/query/* in case of ExpressJS v4 or /api/query/*splat in case of ExpressJS v5 (or any other path specified in your Better Query options).

Don’t use express.json() before the Better Query handler. Use it only for other routes, or the client API will get stuck on "pending".

server.ts
import express from "express";
import { toNodeHandler } from "better-query/node";
import { query } from "./query";

const app = express();
const port = 3005;

app.all("/api/query/*", toNodeHandler(query)); // For ExpressJS v4
// app.all("/api/query/*splat", toNodeHandler(query)); For ExpressJS v5 

// Mount express json middleware after Better Query handler
// or only apply it to routes that don't interact with Better Query
app.use(express.json());

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

After completing the setup, start your server. Better Query will be ready to use. You can send a GET request to the /ok endpoint (/api/query/ok) to verify that the server is running.

Cors Configuration

To add CORS (Cross-Origin Resource Sharing) support to your Express server when integrating Better Query, you can use the cors middleware. Below is an updated example showing how to configure CORS for your server:

import express from "express";
import cors from "cors"; // Import the CORS middleware
import { toNodeHandler, fromNodeHeaders } from "better-query/node";
import { query } from "./query";

const app = express();
const port = 3005;

// Configure CORS middleware
app.use(
  cors({
    origin: "http://your-frontend-domain.com", // Replace with your frontend's origin
    methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
    credentials: true, // Allow credentials (cookies, authorization headers, etc.)
  })
);

Getting the User Session

To retrieve the user's session, you can use the getSession method provided by the query object. This method requires the request headers to be passed in a specific format. To simplify this process, Better Query provides a fromNodeHeaders helper function that converts Node.js request headers to the format expected by Better Query (a Headers object).

Here's an example of how to use getSession in an Express route:

server.ts
import { fromNodeHeaders } from "better-query/node";
import { query } from "./query"; // Your Better Query instance

app.get("/api/me", async (req, res) => {
 	const session = await query.api.getSession({
      headers: fromNodeHeaders(req.headers),
    });
	return res.json(session);
});

On this page