Skip to content

Express Endpoints - Getting started

Introduction

Express endpoints is a framework for astro.js that allows you to create express-like endpoints in astro.js.

Some of the features:

  • ✅ Body, Query, Params, Headers parsers
  • ✅ Express Middleware
  • ✅ JWT session (if you use astro-utils/forms)
  • ✅ Body validator (via zod-express-middleware)
  • ✅ Send JSON, files, and HTML easily

Installation

Terminal window
npm install @astro-utils/express-endpoints

Usage

import { ExpressRoute } from "@astro-utils/express-endpoints";
const router = new ExpressRoute();
router.validate({
body: z.object({
name: z.string()
})
});
export const POST = router.route(async (req, res) => {
await new Promise(res => setTimeout(res, 1000));
res.json({
name: req.body.name,
url: 'This is a POST request'
});
});

The validation options apply only to the next route.

Meaning that you can use the same router for multiple methods.

Body options

The default body-parser is auto meaning that it will parse the body no matter the type of it including multipart/form-data.

You can configure the body parser by calling the body method.

const router = new ExpressRoute();
router.body('multipart', {
maxFileSize: 10 * 1024 * 1024 // 10MB
});
export const POST = router.route((req, res) => {
const myFile = req.filesOne.myFile;
res.json({
name: myFile?.name || 'No file',
});
});

The body parser options are the same as formidable.

You can call the body method multiple times, only the last one will be used for the next route.

router.body('json');
export const POST = router.route((req, res) => {
res.json({
name: req.body.name,
url: 'This is a POST request'
});
});
router.body('multipart', {
maxFileSize: 10 * 1024 * 1024 // 10MB
});
export const PUT = router.route((req, res) => {
const myFile = req.filesOne.myFile;
res.json({
name: myFile?.name || 'No file',
});
});