Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

next-graphql

Package Overview
Dependencies
Maintainers
2
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-graphql

GraphQL for Next.js

  • 2.1.0
  • unpublished
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3
decreased by-85%
Maintainers
2
Weekly downloads
 
Created
Source

Overview

NextGraphQL.js is a zero-config GraphQL server for Next.js, supporting Vercel Serverless environment runtime.

Getting Started

From your main Next.js project path run:

npx next-graphql init

Then, open http://localhost:3000/api/graphql.

Features

  • Easily add any number of GraphQLSchemas together.
  • Built-in support for NextAuth
  • Schema merging + stitching
  • Remote schemas + pruning
  • Extensions
  • Guards on Endpoints + Properties
  • ... and more soon, let us know what features you need!

Examples

Nexus

It's really easy to build a schema using Nexus and NextGraphQL:

// pages/api/graphql.ts

import { extendType, objectType, makeSchema } from "nexus"
import { handler as nextGraphQLHandler } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

const Query = extendType({
  type: "Query",
  definition(t) {
    t.field("hello", {
      type: "String",
      resolve() {
        return "Hello, world"
      },
    })
  },
})

const nexus = makeSchema({
  types: [Query],
})

export default nextGraphQLHandler({
  schemas: {
    nexus,
  },
})

For a complete example, see examples/nexus.

NextAuth

One of the main motivations behind this project was to provide a more integrated experience with GraphQL and Authentication.

Most BaaS services provide some sort of authentication capabilities but having deep auth integration with your project is beneficial.

Adding NextAuth is a few lines of code.

// pages/api/graphql.ts

import { getSession } from "next-auth/client" 
import { handler as nextGraphQLHandler } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  session: ({ req }) => getSession({ req })
  schemas: {
    // ...
  }
})

This will add a {session} object to the resolver context.

Authentication Guards

You can easily guard content:


// pages/api/graphql.ts

import { getSession } from "next-auth/client"
import { handler as nextGraphQLHandler } from "next-graphql"
import { isAuthenticated } from "next-graphql/auth"

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  session: ({ req }) => getSession({ req })
  schemas: {
    // ...
  },
  guards: {
    Query: {
      myQuery: isAuthenticated
    }
  }
})

Remote Schemas

Remote schemas are a first-class citizen in NextGraphQL. By default all schemas are merged and stitched together creating a primary, "gateway" schema.

For a full working remote example, see see examples/remote

Basic remote schema

This will add the SpaceX GraphQL endpoints:

// pages/api/graphql.ts
import { handler as nextGraphQLHandler, remote } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  schemas: {
    spacex: remote("https://api.spacex.land/graphql"),
  },
})

Guarding remote schema endpoints

Now suppose that you want to guard some of the endpoints in the remote schema:

// pages/api/graphql.ts

import { handler as nextGraphQLHandler, remote } from "next-graphql"
import { rule } from "next-graphql/guards"

const fiftyPercentFailWithError = rule()(async (parent, args, ctx, info) => {
  return Math.floor(Math.random() * 100) % 2 === 0 ? true : new Error("You were randomly selected to have this endpoint fail.")
})

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  schemas: {
    spacex: remote("https://api.spacex.land/graphql"),
  },
  guards: {
    Query: {
      ships: fiftyPercentFailWithError
    }
  }
})

Custom headers/authentication

Suppose you want to add an authorized endpoint, i.e. GraphCMS:

// pages/api/graphql.ts

import { handler as nextGraphQLHandler, remote } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  schemas: {
    graphcms: remote(process.env.GRAPHCMS_URL, {
      headers: {
        Authorization: "Bearer " + process.env.GRAPHCMS_TOKEN,
      },
    }),
  },
})

Pruning remote schemas

Sometimes we want to alter the upstream schema. This removes all references to Ship, which will also prune the final schema removing all unused types from the gateway schema.

// pages/api/graphql.ts

import { handler as nextGraphQLHandler, remote } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

export default nextGraphQLHandler({
  schemas: {
    spacex: remote("https://api.spacex.land/graphql", {
      prune: {
        types: (type) => !type.match(/Ship/),
      },
    }),
  },
})

Extensions

NextGraphQL supports an Extension format to make it easy for submodule development:

// pages/api/graphql.ts

import { handler as nextGraphQLHandler, remote } from "next-graphql"

export const config = {
  api: {
    bodyParser: false,
  },
}

const customExtender = {
  resolvers: {
    Query: {
      ships: async (obj, args, context) => {
        return getDataFromOtherSource() // custom override resolver
      }
    }
  }
}

export default nextGraphQLHandler({
  schemas: {
    spacex: remote("https://api.spacex.land/graphql"),
  },
  extensions: [customExtender]
})

Extensions support the following options:

export type Extension = {
  typeDefs?: string
  resolvers?: {
    [key: string]: any
  }
  middleware?: Middleware | Middleware[]
  guards?: Guards
}

Acknowledgements

NextGraphQL is a new project but we're super grateful to all our contributors as we expand and built out the project.

We'd also like to make a massive shoutout to the Guild team for their contributions to GraphQL, without which this project wouldn't exist.

License

MIT

FAQs

Package last updated on 25 Sep 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc