Skip to main content

server.js API

The server.js file is the backend entry point for a Node.js project. It must define a global handleRequest function.

The request Object

The function receives a request object with these properties:

Property Type Description
request.method string HTTP method (GET, POST, etc.)
request.path string Request path (e.g., /api/users)
request.query string Raw query string (e.g., page=1&limit=10)
request.headers object Key-value pairs of request headers
request.body string Raw request body (empty string for GET/HEAD)

The Return Value

The function must return either:

  • A response object — To send a response to the client
  • null — To signal "not handled" (results in 404)

Response Object Format

Field Type Required Description
status number No (default: 200) HTTP status code
headers object No Response headers (key-value)
body string No Response body content

Complete Example

function handleRequest(request) {
    // CORS headers on all responses
    var cors = { 'Access-Control-Allow-Origin': '*' };

    // Simple GET endpoint
    if (request.path === '/api/status' && request.method === 'GET') {
        return {
            status: 200,
            headers: Object.assign(cors, { 'Content-Type': 'application/json' }),
            body: JSON.stringify({
                online: true,
                uptime: process.uptime(),
                timestamp: new Date().toISOString()
            })
        };
    }

    // POST endpoint with JSON body
    if (request.path === '/api/message' && request.method === 'POST') {
        var data = JSON.parse(request.body || '{}');
        return {
            status: 200,
            headers: Object.assign(cors, { 'Content-Type': 'application/json' }),
            body: JSON.stringify({
                reply: 'Hello, ' + (data.name || 'anonymous') + '!'
            })
        };
    }

    // Return null for unhandled paths
    return null;
}

Tips

  • Parse JSON safely: Always provide a default empty object: JSON.parse(request.body || '{}')
  • URL parameters: Parse request.query manually or use a query string parsing library from npm.
  • Error handling: Wrap your logic in try/catch and return appropriate status codes.
  • Headers: Set Content-Type appropriately for your response format.