A single function to be used as a verification for the new JWT app auth, used on the backend to verify FE requests incoming.
npm install shopify-jwt-auth-verifytrue let other stuff happen or false stop stuff from happening.
// Require or Import
const isVerified = require("shopify-jwt-auth-verify")['default']
// OR
import isVerified from 'shopify-jwt-auth-verify'
// use it by passing it the session token from the header ( or getSessionToken) and App secret
const valid = isVerified(headerBearer, appSecret, appKey)
`
Typescript
This function has types supplied and was written in typescript if that is of interest to any one.
Notes:
Requirements: Node 10+
Tested Node Versions
- 10+
- 12+
- 14+
- 15+
- 16+
API
isVerified
const isVerified = (authorization: string, secret: string, cb?: Function ) => boolean
$3
1. authorization - REQUIRED - the jwt passed into the header on the request
2. secret - REQUIRED - app secret ( partners.shopify.com)
3. key - REQUIRED - app key (partners.shopify.com)
4. callback - OPTIONAL - callback called if is verified and passed an object of the header, payload and signature.
5. returnCallback - OPTIONAL - a boolean that if tru will chance the return of callback function, to allow chaining.
The call back is there if needed, but serves little purpose unless you need to extend or assert agains the function.
$3
1. Boolean - true = valid / false = set fire to the ships and back out of the request.
Example as a NextJS Api route middleware
Below is an example of usage in next js api routes to act as the core function in the middleware protecting your backend routes.
`
// Middle Ware : /pages/api/_middleware/jwtVerified
import { NextApiRequest, NextApiResponse } from 'next';
import isVerified from 'shopify-jwt-auth-verify'
const jwtVerifiedConnection = (handler) => {
return async(req: NextApiRequest, res: NextApiResponse) => {
// The authorization header is required for all requests to the api.
if(!req.headers.authorization) {
res.status(403).json({message: 'No bearer supplied, are you using the correct fetch method'})
}
const verified = isVerified(req.headers.authorization, process.env.SHOPIFY_APP_SECRET, process.env.SHOPIFY_APP_KEY)
if(!verified) {
return res.status(401).json({message: 'JWT is invalid.'})
}
// continue on to the route requested.
return handler(req, res)
}
}
export default jwtVerifiedConnection
// Api Route : /pages/api/logme.ts
import { NextApiRequest, NextApiResponse } from 'next';
import jwtVerifiedConnection from '../../_middleware/jwtVerified';
const logme = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(200).json({
body: req.body,
})
}
export default jwtVerifiedConnection(logme)
``