Skip to content

Server routes ​

Server routes are HTTP request handlers which can be anything from an API endpoint to hardcoded redirects. They can be registered in the src/server.js file via the routes function.

js
/** @param {import('crelte/server').ServerRouter} router */
export function routes(router) {
	// redirect from /redirect to /redirected
	router.get('/redirect', csr => Response.redirect(csr.frontendUrl('/redirected')));

	// check if the number in the url matches the number in the body
	router.post('/api/:number/matches', csr => {
		const data = await csr.req.json();
		if (typeof data.number !== 'number') {
			throw new Response('expected number', { status: 400 });
		}

		const number = parseInt(csr.req.getParam('number'));
		if (isNaN(number)) {
			throw new Response('expected number param', { status: 400 });
		}

		return Response.json({ matches: data.number === number });
	});
}

Handler ​

A Handler is a function which takes a CrelteServerRequest and returns a WebApi Response. csr.req is a ServerRequest which is basically a WebApi request with some added properties. The idea behind CreateServerRequest is to be really similar to the main Crelte type allowing for the use of known methods like query.

Query ​

If you only have a simple API you might also be able to just use a handle function inside of a query. See Handle.