---
title: subscriptionType
codeStyle: true
---

## subscriptionType

```ts
subscriptionType(typeName:string, fn: SubscriptionTypeConfig): NexusSubscriptionType
```

Create a GraphQL `Subscription` type.

A subscription type configuration field is like an object type with the following differences:

1. It has a `subscribe` field. You should return an async iterator here. This is called once for each subscription a client sends.
2. The `root` param of the `resolve` field is called for each promise returned by the async iterator setup. The resolver is responsible for transforming the shape of data returned by your subscription stream into types that conform to your GraphQL schema.

Check out this [runnable code sandbox](https://codesandbox.io/s/nexus-example-subscriptiontype-cnenk?file=/src/main.ts).

Here is another runnable example with a minimalistic schema.

```ts
import { ApolloServer } from 'apollo-server-express'
import express from 'express'
import * as HTTP from 'http'
import * as path from 'path'
import { makeSchema, subscriptionType } from '@nexus/schema'

const schema = makeSchema({
  shouldExitAfterGenerateArtifacts:
    process.env.NEXUS_SHOULD_EXIT_AFTER_GENERATE_ARTIFACTS === 'true',
  outputs: {
    typegen: path.join(__dirname, 'node_modules/@types/nexus-typegen/index.d.ts'),
    schema: path.join(__dirname, './api.graphql'),
  },
  types: [
    subscriptionType({
      definition(t) {
        t.boolean('truths', {
          subscribe() {
            return (async function*() {
              while (true) {
                await new Promise(res => setTimeout(res, 1000))
                yield Math.random() > 0.5
              }
            })()
          },
          resolve(eventData) {
            return eventData
          },
        })
      },
    }),
  ],
})

const apollo = new ApolloServer({ schema })
const app = express()
const http = HTTP.createServer(app)

apollo.applyMiddleware({ app })
apollo.installSubscriptionHandlers(http)

http.listen(4000, () => {
  console.log(`🚀 GraphQL service ready at http://localhost:4000/graphql`)
})
```
