Routing

API routes, controllers, and middleware

Route Files

Routes live in src/routes/. Each file default-exports a function that receives the router and registers routes on it. The loader scans the directory recursively at startup and calls that function for every .js file it finds.

The loader only calls a default export when it is a function. A file that default-exports anything else, such as an array of route objects, is skipped without an error or a warning. If a route returns 404 that you are certain you registered, check that the file exports a function.

src/routes/api/posts.js
import { PostController } from '../../controllers/PostController.js'
import { auth } from '../../middleware/auth.js'

export default (router) => {
  // Public routes
  router.get('/api/feed', PostController.feed)
  router.get('/api/feed/:id', PostController.feedShow)

  // Authenticated routes
  router.get('/api/posts', auth, PostController.index)
  router.post('/api/posts', auth, PostController.store)
  router.get('/api/posts/:id', auth, PostController.show)
  router.put('/api/posts/:id', auth, PostController.update)
  router.delete('/api/posts/:id', auth, PostController.destroy)
}

The router supports get, post, put, patch, delete, head and options, plus all to register a path for every method.

Generate a route file
npx basicben make:route post

Controllers

Controllers hold the logic for your routes. Each handler receives the request and the response and is responsible for sending something back.

src/controllers/PostController.js
import { db } from '@basicbenframework/core/db'

export const PostController = {
  // GET /api/posts
  index: async (req, res) => {
    const posts = await (await db.table('posts'))
      .where('user_id', req.userId)
      .orderBy('created_at', 'DESC')
      .get()

    res.json({ posts })
  },

  // GET /api/posts/:id
  show: async (req, res) => {
    const post = await (await db.table('posts')).find(req.params.id)

    if (!post || post.user_id !== req.userId) {
      return res.json({ error: 'Post not found' }, 404)
    }

    res.json({ post })
  },

  // POST /api/posts
  store: async (req, res) => {
    const { title, content } = req.body

    const result = await (await db.table('posts'))
      .only('title', 'content', 'user_id')
      .insert({
        title,
        content,
        user_id: req.userId
      })

    res.json({ id: result.lastInsertRowid }, 201)
  },

  // PUT /api/posts/:id
  update: async (req, res) => {
    const { title, content } = req.body

    await (await db.table('posts'))
      .where('id', req.params.id)
      .where('user_id', req.userId)
      .only('title', 'content')
      .update({ title, content })

    res.json({ success: true })
  },

  // DELETE /api/posts/:id
  destroy: async (req, res) => {
    await (await db.table('posts'))
      .where('id', req.params.id)
      .where('user_id', req.userId)
      .delete()

    res.json({ success: true })
  }
}

db.table() resolves the database connection before it hands back a query builder, so it is awaited once before the chain starts. That is the reason for the doubled await.

From 0.9, insert() and update() throw an error with code: 'MASS_ASSIGNMENT' unless the chain names its columns with .only(...), or opts out with .unguarded(). A key in the object that is not listed is not written.

Generate a controller
npm run make:controller Post

Middleware

Middleware is positional. Pass it between the path and the handler: the last argument is always the handler, and everything before it runs first, in order. A middleware either calls next() to continue or sends a response to stop the chain.

Attaching middleware to a route
router.get('/api/posts', auth, PostController.index)
router.post('/api/posts', auth, rateLimit, PostController.store)
src/middleware/auth.js
import { verifyJwt } from '@basicbenframework/core/auth'

export const auth = async (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '')

  if (!token) {
    return res.json({ error: 'Unauthorized' }, 401)
  }

  const payload = verifyJwt(token, process.env.APP_KEY)

  if (!payload) {
    return res.json({ error: 'Invalid token' }, 401)
  }

  req.userId = payload.userId
  next()
}

Files in src/middleware/ that default-export a function are loaded automatically and applied to every request, in alphabetical order. Middleware you want to apply to specific routes should be a named export instead, as above, and passed to the route explicitly.

Generate middleware
npx basicben make:middleware auth

Route Groups

router.group() shares a path prefix and a set of middleware across several routes. Middleware passed to the group runs before the middleware of any route inside it.

Grouping routes
export default (router) => {
  router.group('/api/admin', auth, requireAdmin, (group) => {
    group.get('/stats', AdminController.stats)
    group.get('/users', AdminController.users)
    group.get('/users/:id', AdminController.showUser)
  })
}

// Registers, each behind auth and requireAdmin:
//   GET /api/admin/stats
//   GET /api/admin/users
//   GET /api/admin/users/:id

Named Routes

Pass a name as a string directly after the path to register the route under that name. router.route() then builds a URL from the name and its parameters, so paths are defined in one place rather than repeated as string literals.

Naming a route and generating its URL
router.get('/api/users/:id/posts', 'users.posts', PostController.byUser)

router.route('users.posts', { id: 42 })
// => '/api/users/42/posts'

From 0.9 the values are URI-encoded, so one with a slash or a space still round-trips through the matcher: router.route('posts.show', { id: 'a/b' }) gives /api/posts/a%2Fb.

The name is picked out by type, not by position: of the arguments between the path and the handler, the first string is the name and the rest are middleware. Both orderings below register the same named route. Put the name straight after the path anyway — it reads better, and it is where the next person will look for it.

The name can sit anywhere among the middleware
router.get('/api/posts/:id', 'posts.show', auth, PostController.show)
router.get('/api/posts/:id', auth, 'posts.show', PostController.show)

// Both give:
router.route('posts.show', { id: 42 })
// => '/api/posts/42'

Before 0.1.17 only the first argument after the path was checked, so a name placed after middleware stayed in the middleware chain and was called as a function at request time. If you are on an older version, keep the name immediately after the path.

Asking for a name that was never registered throws, so a renamed route fails at the call site instead of quietly producing a broken URL.

Resource Routes

router.resource() registers the five standard CRUD routes for a controller. It only registers a route when the matching method exists on the controller, so a controller without a destroy method simply gets no DELETE route.

Registering a resource
router.resource('/api/widgets', WidgetController)

// GET    /api/widgets       -> index     (api.widgets.index)
// GET    /api/widgets/:id   -> show      (api.widgets.show)
// POST   /api/widgets       -> create    (api.widgets.create)
// PUT    /api/widgets/:id   -> update    (api.widgets.update)
// DELETE /api/widgets/:id   -> destroy   (api.widgets.destroy)

Route names are derived from the path. Pass name to set them explicitly and only to limit which routes are generated.

Resource options
router.resource('/api/widgets', WidgetController, {
  name: 'widgets',
  only: ['index', 'show']
})

// GET /api/widgets      -> widgets.index
// GET /api/widgets/:id  -> widgets.show

Pass middleware to put every generated route behind it. Wrapping the resource in a group does the same thing and is the better choice when other routes share the same guard.

Middleware on a resource
// Directly on the resource
router.resource('/api/widgets', WidgetController, {
  name: 'widgets',
  middleware: [auth]
})

// Or through a group, which other routes can share
router.group('/api', auth, (group) => {
  group.resource('/widgets', WidgetController, { name: 'widgets' })
})

The middleware option was unusable before 0.1.17, when the generated route name was still read positionally: the option placed the middleware ahead of the name, which left the name in the chain and made every route in the resource fail with a 500. On an older version, use the group.

Route Parameters

Path segments written as :name are captured into req.params. Query strings are parsed into req.query, and the pathname is available as req.path.

Parameters and query strings
// Route: /api/posts/:id
// URL:   /api/posts/123?include=author

export const show = async (req, res) => {
  const { id } = req.params        // { id: '123' }
  const { include } = req.query    // { include: 'author' }

  req.path                         // '/api/posts/123'
}

Params arrive URI-decoded: /tags/caf%C3%A9 gives 'café'. The exceptions are %2F and %5C, which stay encoded, so a param never gains a path separator it did not have. A malformed escape gets a plain 400 with { "error": "Bad Request" }. Before 0.9, params arrived still encoded.

A query key given once is a string. A key given more than once is an array of every value, in order. Check the type before calling string methods on a query value.

Repeated query keys
// URL: /api/posts?tag=a&tag=b&sort=new
req.query  // { tag: ['a', 'b'], sort: 'new' }

const tags = typeof req.query.tag === 'string'
  ? [req.query.tag]
  : req.query.tag ?? []

A trailing /* matches everything below a path and captures the remainder as req.params._catchAll, decoded the same way.

Everything in a route other than :name and * is literal: the . in /feed.xml matches only a dot. Trailing slashes are ignored, so /about/ reaches the /about route. A HEAD request with no HEAD route of its own runs the GET route; no body is sent, but the response carries the Content-Length the GET would have sent when the route ends with a single res.end(body).

Request Body

JSON request bodies are parsed automatically and made available on req.body. The body parser is enabled by default with a 1mb limit, configurable through bodyParser in basicben.config.js.

Accessing the request body
export const store = async (req, res) => {
  const { title, content, published } = req.body

  if (!title) {
    return res.json({ error: 'Title is required' }, 400)
  }

  // ...
}

Response Helpers

Every response object carries four helpers.

Sending responses
res.json({ posts })              // 200 with a JSON body
res.json({ error: 'Gone' }, 410) // status and JSON body together
res.send('plain text')           // text, or JSON if given an object
res.redirect('/login')           // 302 by default
res.redirect('/login', 301)      // or an explicit status
res.status(204)                  // sets the status, returns res

Both ways of setting a status work. res.json() applies its second argument when you pass one and otherwise keeps whatever res.status() already set, so an explicit second argument wins over an earlier res.status() call.

Either form
res.json({ error: 'Not found' }, 404)   // 404
res.status(404).json({ error: 'Not found' })  // 404

Before 0.1.15 res.json() defaulted its status to 200 and applied it unconditionally, so res.status(404).json(...) answered 200. Passing the code to res.json() directly is correct on every version, which is why the examples here do it that way.

Client Routing

The browser side has its own router. createClientApp() takes a map of paths to components and returns a React component to render. A path maps either to a component directly, or to an object that can also set a layout and a guard.

src/routes/App.jsx
import { createClientApp } from '@basicbenframework/core/client'
import { AppLayout } from '../client/layouts/AppLayout'
import { AuthLayout } from '../client/layouts/AuthLayout'
import { Home } from '../client/pages/Home'
import { Auth } from '../client/pages/Auth'
import { Posts } from '../client/pages/Posts'
import { PostForm } from '../client/pages/PostForm'

export default createClientApp({
  layout: AppLayout,
  routes: {
    '/': Home,
    '/login': { component: Auth, layout: AuthLayout, guest: true },
    '/posts': { component: Posts, auth: true },
    '/posts/:id/edit': { component: PostForm, auth: true }
  }
})

auth: true redirects to /login when nobody is signed in. guest: true does the reverse and redirects to / when someone is, which keeps signed-in users off the login page. layout replaces the app-wide layout for that route only.

Guards redirect after render: the route renders nothing, and an effect navigates with replace. Client patterns use the server's matcher, so params, literal dots and trailing slashes behave the same on both sides. * works on its own, to match every path, or as a trailing /*; a * in the middle of a path is literal.

Client config options
createClientApp({
  routes,
  authEndpoint: '/api/user',          // read the signed-in user on load; false skips it
  logoutEndpoint: '/api/auth/logout', // POSTed on logout; false skips it
  loginPath: '/login',                // where auth routes send signed-out visitors
  homePath: '/'                       // where guest routes, and logout, send you
})

The values shown are the defaults.

Hooks
import { useAuth, useNavigate, useParams, usePath, useSearch, useSearchParams } from '@basicbenframework/core/client'

export function EditPost() {
  const { user, logout, loading } = useAuth()
  const navigate = useNavigate()
  const { id } = useParams()
  const path = usePath()
  const search = useSearch()                  // '?page=2', or ''
  const [params, setParams] = useSearchParams()

  // navigate('/posts')
  // navigate('/posts', { replace: true })
  // navigate('/posts?page=2#top')
  // navigate('https://example.com')          // another origin: a full page load

  // setParams({ page: 3 })
  // setParams(prev => { prev.set('page', '3'); return prev }, { replace: true })
}

navigate() takes a path with a query string or hash, or a full URL. A URL on another origin is a full page load. useSearchParams() returns a URLSearchParams and a setter that takes a URLSearchParams, a string, an object or a function of the current params, and keeps the path and hash.

Link
import { Link } from '@basicbenframework/core/client'

<Link to="/posts">Posts</Link>
<Link to="/posts?page=2" replace>Next</Link>

Link renders a real <a href>. A plain left click on a same-origin link navigates without a page load; modified clicks, a target other than _self, download and other origins are left to the browser.

These hooks read context that createClientApp provides, so they throw if called from a component rendered outside it.

Deep Links in Production

In production the server serves the built client from static.dir. A request for /posts/1 looks for a file at that path, finds none, and returns 404, so the client router never gets a chance to run. Deep links and page refreshes break even though the same URLs work in development.

Setting spa: true serves index.html for unmatched routes instead, letting the client router take over.

basicben.config.js
export default {
  static: {
    dir: 'public',
    spa: true
  }
}

The fallback runs only after route matching, so it cannot shadow your API. Requests under /api/ and requests for files with a non-HTML extension still return 404, which means a missing script reports as missing rather than returning the app shell with the wrong content type. Available from 0.1.14.