Need Guidance on JWT Validation in Node.js Using Appwrite SDK

83 Views Asked by At

Seeking help with JWT validation in a Node.js backend using the Appwrite SDK. Currently designing our backend, successfully implemented JWT creation on Flutter client side. However, facing challenges with JWT validation on Node.js server, particularly while creating a new post.

Currently, our post creation method looks like this:

const { config, attrs, enums } = require('./config');
const sdk = require("node-appwrite");
const client = new sdk.Client();

client.setEndpoint(config.endpoint);
client.setProject(config.projectId);
client.setKey(config.key);

const databases = new sdk.Databases(client);

const createPost = async (newPost) => {
    return await databases.createDocument(config.databaseId, config.collectionPostsId, sdk.ID.unique(), newPost);
}

Now, we want to include JWT validation in the createPost method:

const createPost = async (token, newPost) => {
    // Validate the token with the SDK method here
    // ...

    return await databases.createDocument(config.databaseId, config.collectionPostsId, sdk.ID.unique(), newPost);
}

In our research, we found the Appwrite documentation on JWT. However, we are struggling to understand how to validate a user with their token in our specific scenario. The documentation shows setting the JWT on the Appwrite Client object:

const { Client } = require('node-appwrite');

const client = new Client()
    .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
    .setProject('<PROJECT_ID>') // Your project ID
    .setJWT('eyJJ9.eyJ...886ca'); // Your secret JSON Web Token

Our confusion lies in the fact that user-specific information like the JWT is set on an application-specific object (Client). We would like guidance on how to properly validate a user with their token in our scenario:

const createPost = async (token, newPost) => {
    // Validate the token with the SDK method here
    // ...

    return await databases.createDocument(config.databaseId, config.collectionPostsId, sdk.ID.unique(), newPost);
}

We appreciate any insights or code examples that can help us better understand and implement JWT validation in our Node.js backend using the Appwrite SDK.

Thank you in advance for your assistance!

1

There are 1 best solutions below

0
On

You'd use the account.get() method.

In your createPost function, you need an Account object (const account = new Account(client), where client is the Client instance you've called setJWT() on).

Calling account.get() will throw an Exception if the JWT isn't valid for whatever reason. If the JWT is valid, it will return a user object.