set input or output context dialogflow nodejs v2

I am using dialogflow NPM module and I want to send input/output context but I am not sure how to do. I know I can do in google-assistant NPM with I can set contexts with parameter using below method,

 const parameters = { // Custom parameters to pass with context
     welcome: true,
 conv.contexts.set('welcome-context', 5, parameters);

In order to send a context using the Dialogflow NPM module, you have to first create a context, using dialogflow.ContextsClient and then send it on the query.

To convert the parameters to the format required by Dialogflow you will need to use this module: pb-util

const dialogflow = require('dialogflow');
const { struct } = require('pb-util');  

const projectId = 'projectId';
const contextsClient = new dialogflow.ContextsClient();
const sessionClient = new dialogflow.SessionsClient();

async function createContext(sessionId, contextId, parameters, lifespanCount = 5) {

    const sessionPath = contextsClient.sessionPath(projectId, sessionId);
    const contextPath = contextsClient.contextPath(

    const request = {
        parent: sessionPath,
        context: {
            name: contextPath,
            parameters: struct.encode(parameters)

    const [context] = await contextsClient.createContext(request);

    return context;

function sendQuery(sessionId, query, context) {

    const session = sessionClient.sessionPath(projectId, sessionId);

    const request = {
        queryInput: {
            text: {
                text: query
        queryParams: {
            contexts: [context] // You can pass multiple contexts if you wish

    return sessionClient.detectIntent(request);

(async() => {
    const parameters = { // Custom parameters to pass with context
       welcome: true

    const sessionId = 'my-session';
    const context = await createContext(sessionId, 'welcome-context', parameters);

    const response = await sendQuery(sessionId, 'Hi', context);



Have in mind that you send an input context. The output context is generated in the intent.

If you have trouble authenticating the clients SessionClient & ContextClient you can check this other question: Dialogflow easy way for authorization

The output context is dogs, so it becomes the active context. When the end-user says I like cats: The pet-select-cats intent is matched. The output context is cats, so it becomes the active context. When the end-user says What do they look like?: If dogs is the active context: The dog-show intent is matched. The end-user is shown a dog picture.

Go to the Dialogflow Console. Select an agent. Select Intents in the left sidebar menu. Expand the Contexts section of the intent data. Click the Add output context or Add input context field in

Building on Marco's excellent answer-- here's a simpler version:


  "name": "credtest",
  "version": "1.0.0",
  "dependencies": {
    "dialogflow": "^1.2.0",
    "pb-util": "^0.1.3"


const {ContextsClient} = require('dialogflow')
const { struct } = require('pb-util');  


1. Service Account Credential file (KEEP SAFE)
// where/how to get this key:
// For different auth options, see Marco Casagrande's explainer:
// Note: JSON hard-coded below for copy/paste, just import/require in when using for real

const credential = {
    "type": "__REPLACE__ME___",
    "project_id": "__REPLACE__ME___",
    "private_key_id": "__REPLACE__ME___",
    "private_key": "__REPLACE__ME___",
    "client_email": "__REPLACE__ME___",
    "client_id": "__REPLACE__ME___",
    "auth_uri": "__REPLACE__ME___",
    "token_uri": "__REPLACE__ME___",
    "auth_provider_x509_cert_url": "__REPLACE__ME___",
    "client_x509_cert_url": "__REPLACE__ME___"

2. Project ID, Google cloud project id
Tip: notice the service-account naturally already has your product id
const project_id = '__REPLACE__ME___' // This is your google cloud project

const client = new ContextsClient({
    credentials: credential

createContext('123456789', {name: 'bongo_context', lifespanCount: 3, parameters: {a:1, b:2, c:3 }} )

function createContext(sessionID, {name, lifespanCount, parameters = {} } = {} ) {
    const formattedParent = client.sessionPath(project_id, sessionID);
    const formattedContextName = `projects/${project_id}/agent/sessions/${sessionID}/contexts/thebongocontext`
    const context = {
        "name": formattedContextName,
        "lifespanCount": 2,
        "parameters": struct.encode(parameters)

    const request = {
        parent: formattedParent,
        context: context,

          .then(responses => {
            const response = responses[0];
            console.log('context now active:', response)
          .catch(err => {


Dialogflow webhook set parameter value. 0. Dialogflow fulfillment chose among options. 1. set input or output context dialogflow nodejs v2. Hot Network Questions

Node.js client for Dialogflow: Design and integrate a conversational user interface into your applications and devices. - googleapis/nodejs-dialogflow

Warning: The Dialogflow V1 API shutdown has been postponed to May 31st, 2020. Read more details here. Note: The multi-language feature does not affect this endpoint. The /contexts endpoint allows you to get active contexts, add new contexts, or delete active contexts for the specified session Id.

Changes in V2. Here are the high-level changes you can expect and should be aware of when moving to V2 of the API: How agents are accessed via the API, both at runtime and designtime. New Webhook API protocol. How one-click integrations call Dialogflow - This shouldn't affect you, as the changes are on our end.