DEV Community

Cover image for The New HTTP QUERY Method: How to Use It in Node.js and Express Today
Dev Encyclopedia
Dev Encyclopedia

Posted on

The New HTTP QUERY Method: How to Use It in Node.js and Express Today

There's a new HTTP method called QUERY. It's safe like GET (doesn't change data) but can carry a body like POST (so you can send filters). This means search endpoints no longer need the old POST /search trick.

Let's see how to use it in Node.js and Express.

Plain Node.js

Node already understands QUERY, no setup needed.

const http = require('node:http');

const server = http.createServer((req, res) => {
  if (req.method === 'QUERY') {
    let body = '';
    req.on('data', (chunk) => body += chunk);
    req.on('end', () => {
      const filters = JSON.parse(body);
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ results: [], filters }));
    });
    return;
  }
  res.writeHead(404);
  res.end();
});

server.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Test with curl:

curl -X QUERY http://localhost:3000 \
  -H "Content-Type: application/json" \
  -d '{"category":"electronics"}'
Enter fullscreen mode Exit fullscreen mode

Express

Express doesn't support app.query() yet, so add a small check before your routes:

const express = require('express');
const app = express();
app.use(express.json());

app.use((req, res, next) => {
  if (req.method === 'QUERY' && req.path === '/products') {
    const filters = req.body;
    return res.json({ results: [], filters });
  }
  next();
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

That's it. express.json() already parses the body, no extra config needed.

One gotcha: CORS

If your frontend and backend are on different domains, add QUERY to your CORS methods, or the browser will silently block it:

app.use(cors({
  methods: ['GET', 'POST', 'QUERY', 'OPTIONS'],
}));
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Node.js: works out of the box
  • Express: needs a small manual check (shown above)
  • Browsers: support is still patchy, so keep a POST fallback for now

Full article with more details: https://devencyclopedia.com/blog/http-query-method-express-nodejs

Top comments (0)