Search code examples
websocketmemgraphdb

Can I connect to Memgraph using websocket?


Does Memgrpah support connections over WebSocket? I couldn't find the minimal required code to do that.


Solution

  • All that you need is a client that uses WebSocket to connect to Memgraph, and Memgraph will automatically recognize the nature of the connection. The port you will be connected to remains the same.

    You should use Memgraph's address and the port number defined by the configuration flag --bolt-port to connect to Memgraph (7687 is the default port).

    To connect to memgraph via WebSocket you can use the JavaScript client. Minimal code to connect would be:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <title>Javascript Browser Example | Memgraph</title>
        <script src="https://cdn.jsdelivr.net/npm/neo4j-driver"></script>
      </head>
      <body>
        <p>Check console for Cypher query outputs...</p>
        <script>
          const driver = neo4j.driver(
            "bolt://localhost:7687",
            neo4j.auth.basic("", "")
          );
    
          (async function main() {
            const session = driver.session();
    
            try {
              await session.run("MATCH (n) DETACH DELETE n;");
              console.log("Database cleared.");
    
              await session.run("CREATE (alice:Person {name: 'Alice', age: 22});");
              console.log("Record created.");
    
              const result = await session.run("MATCH (n) RETURN n;");
    
              console.log("Record matched.");
              const alice = result.records[0].get("n");
              const label = alice.labels[0];
              const name = alice.properties["name"];
              const age = alice.properties["age"];
    
              if (label != "Person" || name != "Alice" || age != 22) {
                console.error("Data doesn't match.");
              }
    
              console.log("Label: " + label);
              console.log("Name: " + name);
              console.log("Age: " + age);
            } catch (error) {
              console.error(error);
            } finally {
              session.close();
            }
    
            driver.close();
          })();
        </script>
      </body>
    </html>
    

    You can find more info at Memgraph documentation site.