Routing

zely.js automatically generates routes based on your file tree of pages.

filenameresult(path)
/index.ts/
/hello.ts/hello
/foo/bar.ts/foo/bar
/user/$id.ts/user/:id
/user/$id/about.ts/user/:id/about

You can also use nextjs style routes

#Method

Exports functions corresponding get, post, delete etc (http verbs)

Typescript
// get
export function get(req, res) {}
// post
export function post(req, res) {}
// etc...

#Export default

You can write simpler code that outputs the same result since v1.0.

export default
import { ServerDataHandler } from 'zely';
import { GET, POST } from 'zely/methods';
 
export default [
  // simple usage
  GET({ foo: 'bar' }),
  // access to req and res
  POST(ctx => ({
    id: ctx.params.id;
  })),
] as ServerDataHandler[];

See context documentation.

#Route Parameters

You can access the current page parameters by req.params.

pages/user/$id.ts
import { ZelyRequest, ZelyResponse } from 'zely';
 
export function get(req: ZelyRequest, res: ZelyResponse) {
  res.json({ id: req.params.id });
}

#Routes using Brackets

If you don't like zely routes style you can use nextjs routes style.

zely.config.ts
import { defineConfig } from 'zely';
 
export default defineConfig({
  useBrackets: true,
});

Examples:

filenameresult(path)
/index.ts/
/hello.ts/hello
/foo/bar.ts/foo/bar
/user/[id].ts/user/:id
/user/[id]/about.ts/user/:id/about
/foo/[...bar]/foo/:bar*

#Custom Path

If you don't like routes based on filename, just export $page!

Typescript
export const $page = {
  path: '/foo/bar',
};

#404 page

You can set 404 page with config.error.

Typescript
export default defineConfig({
  error(req, res) {
    // ...
    res.status(404).end('page not found');
  },
});

#request and response

Zely Server is based on node:http module.

request

reference: http.req

response

reference: http.res