What is the best way to create a cookie within a tsoa endpoint?

I am currently working with an express server and using tsoa to define my endpoints.

One of the endpoints on my server is a login endpoint that returns an authentication token, which I then store in the browser of a web application:

@Route('auth')
@Tags('Auth')
export class AuthController extends Controller {
  @SuccessResponse('200', 'Returns Token')
  @Post('/login')
  public async login(@Body() body: TokenRequest): Promise<TokenResponse> {
    // ... login implementation.

    return token
  }
}

Now, I am developing a second application that will be hosted on a subdomain of the same domain as the first application. I want both applications to share the same authentication token. To achieve this, I need to set an authentication token (and refresh token) cookie. However, I am unable to find any documentation in tsoa or express on how to accomplish this.

Ideally, I would like my login function to look something like this:

@Post('/login')
public async login(@Body() body: TokenRequest, @Response() res: Response): Promise<TokenResponse> {
  // ... login implementation.
  res.setHeader(...) // or 
  cookie.set(...)
  return token
}

The issue is that I cannot access the express response within the tsoa endpoint. I have also attempted to use the setHeader method on the tsoa Controller class, but it does not work either.

Can anyone provide guidance on how to proceed? Am I approaching this problem from the wrong angle?

Answer №1

There were a few key components that were missing from my setup:

  • When sending a post request with axios, I forgot to include the option "withCredentials: true"
  • In my express cors middleware, I overlooked adding "credentials: true" to ensure cookies could be transmitted
  • To set the cookie at the end, I utilized Controller.setHeader provided by tsoa

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the benefits of using Express in NodeJS to run both a backend and a frontend server simultaneously?

My current project involves a simple NodeJS/AngularJS application structured as follows: /frontend/index.html <-- AngularJS home page /frontend/js/app.js <-- AngularJS app.js /backend/package.json<-- NodeJS package.json /backend/index.js < ...

Executing a method from a callback within the data() function in Vue 2.7 – Here's how!

This component uses a third-party module known as HelloWorld. This module has a prop called closeCallbacks, which is an array of callbacks that are triggered when the HelloWorld component is closed. Unfortunately, the functionality of the third-party comp ...

Utilize data binding in Typescript to easily link variables between a service and controller for seamless utilization

Is there a way to overcome the issue of value assignment not binding data in this scenario? For example, using this.arrayVal = someService.arrayVal does not work as intended. The objective is to simplify the assignment in both HTML and controller by using ...

How to Dynamically Determine if a Value Matches a Union Type in Typescript

After creating a Union type of supported methods, the goal is to verify if a specific method belongs to the set of supported methods and then execute it dynamically. One commonly used approach is to use an array containing the names of the supported method ...

Exploring the use of dynamic mount points in middleware?

I am looking to serve static assets for paths that have a cache buster at the beginning: example.com/40/app.js example2.com/5/hello/hello.js example2.com/60000/hello/world/some-file.js Is it possible with Express? I tried creating a custom middleware ...

Problem with Mongoose callback persistence when utilizing Forever module

Recently, I embarked on a mission to set up a background process using Forever to regularly update my MongoDB database with data from an external service. Being new to Node.js, I was initially clueless about how to tackle this task. Employing Node with Exp ...

What function is missing from the equation?

I am encountering an issue with an object of type "user" that is supposed to have a function called "getPermission()". While running my Angular 7 application, I am getting the error message "TypeError: this.user.getPermission is not a function". Here is w ...

Facing issues with EditorJS not appearing? Learn how to troubleshoot this problem

I am currently in the process of setting up a blog using EditorJS as my blog-post editor. To do this, I am utilizing nodejs, express, and ejs. However, I seem to be encountering an issue as I cannot seem to see the EditorJS interface on my screen. Below is ...

Challenge with TypeScript typing (slightly connected to (P)React)

[Update: I've revised my initial query] Let's say I aim to specify UI components in the exact manner outlined below (the following lines are non-negotiable - any solution that alters these lines is not what I'm seeking): // Please refrain ...

What are the consequences of not subscribing to an HttpClient request that returns observables in an Angular application?

Exploring Angular and TypeScript, I am currently delving into the concepts of HttpClient, observables, and subscribe. When I include the following code in a component function: console.log(this.http.get('assets/user.json')); I receive an objec ...

Using TypeScript's union type to address compatibility issues

Below is a small example I've created to illustrate my problem: interface testType { id: number } let t: testType[] = [{ id: 1 }] t = t.map(item => ({ ...item, id: '123' })) Imagine that the testType interface is source ...

When I try to refresh the Heroku page, all I see is the API information and not

I recently launched a PERN stack application on Heroku. Everything seems to be running smoothly, but I encountered an issue when trying to refresh the page at this specific URL - - as it only displays API information: { "id": 1, "title": "Earth Nights #1 ...

developing versatile paths with Node.js

app.js // Including Routes require("./routes")(app); router folder index.js module.exports = function (app) { app.use("/", require("./all_routes")); } all_routes.js var express = require("express"); var route ...

Node.js: Employing Node.js to Input Information into an Excel Spreadsheet

I have recently developed a Rest API using the express framework that includes a route for exporting data. The information that needs to be exported to an excel file is currently stored in multiple arrays, and I want the excel file to have a specific prede ...

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

Guide on implementing an enum as a type by attaching it to a class as a static variable

// file1.ts enum Variant { Success = 'success', Error = 'error', } export class Example { static Variant = Variant; } // file2.ts import { Example } from './file1'; type Props = { variant: Example.Variant; // TS2 ...

What is the best way to activate a button based on the presence of a cookie?

As I develop my web application, I am faced with the challenge of catering to both guests and registered users. I want to provide a 'Log out' button exclusively for registered users after they have logged in. One solution I am considering is to d ...

Angular $resource failing to transfer parameter to Express endpoint

I am currently working on an Angular application that needs to retrieve data from a MongoDB collection. To accomplish this, I am utilizing the $resource service within the flConstruct. The "query" function works well as it returns all data from the server ...

Updating the variable name from db to a more user-friendly format

When a user selects items from a dropdown menu, the data is saved to the database in uppercase. I need to retrieve an item from the database and display it in a more user-friendly format. TS -- convertItem() { const oldValue = this.rows.map(item => i ...

Error: The choropleth() function received an invalid keyword argument 'color_discrete_map'

When attempting to create a choropleth map, I encountered an error stating that the keyword "color_dicrete_map" is unexpected. Can anyone provide assistance with this issue? def plot_vaccin(color, vaccin): fig = px.choropleth(country_latest, location ...