I wanted to use elastic search for log collection in next.js, but I get this error :
⨯ node:console
Module build failed: UnhandledSchemeError: Reading from "node:console" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
Import trace for requested module:
node:console
./node_modules/undici/lib/mock/pending-interceptors-formatter.js
./node_modules/undici/lib/mock/mock-agent.js
./node_modules/undici/index.js
./node_modules/@elastic/transport/lib/connection/UndiciConnection.js
./node_modules/@elastic/transport/lib/connection/index.js
./node_modules/@elastic/transport/index.js
./node_modules/@elastic/elasticsearch/index.js
./src/lib/logger.ts
Here’s my code
// src/lib/logger.ts
import { Client } from "@elastic/elasticsearch";
const client = new Client({
node: "http://localhost:9200/",
});
export default class Logger {
static async log(index: string, body: object) {
await client.index({ index, body });
}
}
// src/middleware.ts
import { NextRequest } from "next/server";
import Logger from "@/lib/logger";
export async function middleware(request: NextRequest) {
// ...
Logger.log("cb-request-logs", {
user: session.user._id,
url: request.url,
userAgent: request.headers.get("User-Agent"),
});
// ...
}
My environment:
node v20
nextjs v14.2.7
@elastic/elasticsearch ^8.15.0
I noticed that the node address you used is http
and not https
. Was this intentional? (If not, try using node: "https://localhost:9200"
.
NOTE: I removed the trailing ‘/’ so node: "https://localhost:9200"
and NOT node: "https://localhost:9200/"
-
https is required be default by Elasticsearch
-
Quick Check: You can check to see that your Elasticsearch is running properly by running these commands to test the endpoints (Also, are you using Mac or Docker? Slightly different command depending on system):
Mac: curl --cacert $ES_HOME/config/certs/http_ca.crt -u elastic:$ELASTIC_PASSWORD https://localhost:9200
Docker: curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD https://localhost:9200
If you get errors you can try following the installation on Mac and Docker respectively.
- If you don’t want to use HTTPS you can follow this guide and remember to stop/restart Elasticsearch. (This path is NOT recommended and only for experimentation.)
the main point of point 3 is to go into the config file (elasticsearch.yml
) and change the following settings from true to false:
xpack.security.transport.ssl.enabled: true
xpack.security.http.ssl.enabled: true
Again Point 3 is NOT the recommended approach but mentioned for learning/experimenting.