Skip to content

How do I acces headers? #94

Answered by kwhitley
Milo123459 asked this question in Q&A
Mar 4, 2022 · 2 comments · 5 replies
Discussion options

You must be logged in to vote

Here's an example from my own auth layer (within Workers):

// middleware/withAuthenticatedUser.js
import jwt from 'jsonwebtoken'
import { error } from 'itty-router-extras'
import { User } from './User' // external User class, unimportant what it actually does

const JWT_SECRET = 'something super secret'

export const withAuthenticatedUser = request => {
  try {
    const authHeader = request.headers.get('authorization')
    const token = authHeader.replace(/^Bearer\s/i, '')
    const decoded = jwt.verify(token, JWT_SECRET)
    req.user = new User(decoded.user) // should throw if no user
  } catch (err) {
    return error(401, 'Unauthorized') // this will prematurely exit itty handlers and…

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
4 replies
@Milo123459
Comment options

@Milo123459
Comment options

@kwhitley
Comment options

@andrekutianski
Comment options

Answer selected by Milo123459
Comment options

You must be logged in to vote
1 reply
@kwhitley
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
documentation Improvements or additions to documentation
4 participants