neo4j-javascript-driver icon indicating copy to clipboard operation
neo4j-javascript-driver copied to clipboard

`neo4j.driver(process.env.NEO4J_URI)` works some places in the app, and needs hard-coded other places

Open corysimmons opened this issue 2 years ago • 0 comments

image

I'm trying to hook up @neo4j/graphql in a Next.js app with Apollo on the server and client.

  • When I go to initialize this driver on the server with process.env.NEO4J_URI (and process.env username/pass), it works fine.
  • When I go to initialize this driver on the client with process.env.NEO4J_URI (and process.env username/pass), it fails.

You can repro this by cloning the Next.js example Neo4j project and swapping out apollo/client with this:

import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client'
import merge from 'deepmerge'
import { Neo4jGraphQL } from "@neo4j/graphql";
import neo4j from "neo4j-driver";

import typeDefs from '~/schema';

let apolloClient: ApolloClient<any> | null = null

const driver = neo4j.driver(
  // This seems like a bug in Neo4j. This works elsewhere in the app.
  // process.env.NEO4J_URI!,
  "neo4j+s://jsidjdisjfdis.databases.neo4j.io:7687", // Sure wish this wasn't hard-coded...
  neo4j.auth.basic(process.env.NEO4J_USER!, process.env.NEO4J_PASSWORD!)
);

const neoSchema = new Neo4jGraphQL({
  typeDefs,
  driver,
})

function createIsomorphLink() {
  if (typeof window === 'undefined') {
    const { SchemaLink } = require('@apollo/client/link/schema')
    neoSchema
      .getSchema()
      .then(schema => {
        return new SchemaLink({ schema })
      })
  } else {
    const { HttpLink } = require('@apollo/client/link/http')

    return new HttpLink({
      uri: '/api/graphql',
      credentials: 'same-origin',
    })
  }
}

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: createIsomorphLink(),
    cache: new InMemoryCache(),
  })
}

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient()

  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract()

    // Merge the existing cache into data passed from getStaticProps/getServerSideProps
    const data = merge(initialState, existingCache)

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data)
  }

  if (typeof window === 'undefined') return _apolloClient

  if (!apolloClient) apolloClient = _apolloClient

  return _apolloClient
}

export function useApollo(initialState: any) {
  const store = useMemo(() => initializeApollo(initialState), [initialState])
  return store
}

It fails like this too with the ./util/neo4j.js helper as well.

corysimmons avatar Jun 09 '22 01:06 corysimmons