next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

How can I add my own express routes?

Open gielcobben opened this issue 8 years ago • 6 comments

How can we add our own express routers?

example:

server.use("/api/v1/users", users);

gielcobben avatar Jan 29 '18 11:01 gielcobben

Great question! The nextjs-starter project actually does this.

The simplest way to do it is to not pass a port to NextAuth, in which case you can use the instance of Express it returns and then set the Next.js routing behaviour and start Express listening after you have added your custom routes:

'use strict'

const next = require('next')
const nextAuth = require('next-auth')
const nextAuthConfig = require('./next-auth.config')

const nextApp = next({
  dir: '.',
  dev: (process.env.NODE_ENV === 'development')
})

nextApp
.prepare()
.then(() => {
  return nextAuthConfig()
})
.then(nextAuthOptions => {
  // Don't pass a port to NextAuth!
  if (nextAuthOptions.port) delete nextAuthOptions.port

  return nextAuth(nextApp, nextAuthOptions)
})
.then(nextAuthApp => {

  // Get instance of Express from NextAuth instance
  const express = nextAuthApp.express

  // Configure additional routes here
  express.use("/api/v1/users", users);
  
  // Default catch-all handler to allow Next.js to handle all other routes
  express.all('*', (req, res) => {
    let nextRequestHandler = nextApp.getRequestHandler()
    return nextRequestHandler(req, res)
  })

  express.listen(process.env.PORT, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:' + process.env.PORT)
  })
})
.catch(err => {
  console.log('An error occurred, unable to start the server')
  console.log(err)
})

If you want to do stuff with Express before you call NextAuth, you can also pass an Express instance to it, which it will use if passed:

'use strict'

const next = require('next')
const nextAuth = require('next-auth')
const nextAuthConfig = require('./next-auth.config')

// You can define a your own Express instance here and do stuff before passing
// it to NextAuth if you want
const express = require('express')
const expressApp = express()

const nextApp = next({
  dir: '.',
  dev: (process.env.NODE_ENV === 'development')
})

nextApp
.prepare()
.then(() => {
  return nextAuthConfig()
})
.then(nextAuthOptions => {

  // Pass your own Express instance to NextAuth - and don't pass a port!
  if (nextAuthOptions.port) delete nextAuthOptions.port
  nextAuthOptions.expressApp = expressApp

  nextAuth(nextApp, nextAuthOptions)
  
  // Configure additional routes here
  expressApp.use("/api/v1/users", users);
  
  // Default catch-all handler to allow Next.js to handle all other routes
  expressApp.all('*', (req, res) => {
    let nextRequestHandler = nextApp.getRequestHandler()
    return nextRequestHandler(req, res)
  })

  expressApp.listen(process.env.PORT, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:' + process.env.PORT)
  })
})
.catch(err => {
  console.log('An error occurred, unable to start the server')
  console.log(err)
})

iaincollins avatar Jan 29 '18 12:01 iaincollins

Have updated my response to fix a typo.

Feel free to re-open this issue if it's not resolved for you!

iaincollins avatar Jan 29 '18 12:01 iaincollins

Hi,

I tried this but when I make a request to the API route from getInitialProps it initializes a new session in the session store. Is there anything I can do to prevent that?

ghost avatar Jul 20 '18 00:07 ghost

Great question!

Client Side HTTP Calls

If happening on the client side, it is probably happening because you are not sending session cookies with your AJAX request so the server doesn't see that you already have a session.

Try using fetch (or isomorphic-fetch) with the credentials: 'same-origin' option, which tells the browser to attach the session cookie to the request. Note that the session cookie cannot be read from JavaScript (by design). XMLHttpRequest does this automatically.

fetch('/api/my-endpoint', {
  credentials: 'same-origin'
})
.then(response => {
   // …
})

Server Side HTTP Calls

If it is happening when you make calls to an HTTP endpoint from code running server side that's a bit of a different story. Code running server side will of course not have a session cookie (as the cookie lives on the client only).

There is actually a pull request https://github.com/iaincollins/next-auth/pull/23 from @rmcalvert addresses the fact that new sessions get created automatically by default and - when I'm back off my holiday early next month I plan on merging it in.

So, you will automatically stop seeing this behaviour in a future update, as sessions will only be created when you users log in (and nothing will be saved until then). This is better than the more classic session behaviour, which creates a session for every new client it thinks it sees up front (leaving them to be expired if they are never used).

I haven't just merged this update in already as I'm going to switch CSRF over to a different model - as currently it depends on the classic session behaviour. In future the CSRF Token will use the Double Submit Cookie method to continue to provide Cross Site Request Forgery protection (which is equally secure, but works differently and is more lightweight).

Supporting Isomorphic Calls That Need Authentication

If you need to be able to make authenticated calls from both the client and the server, you can pass the req object from getInitialProps({req}) your function and you can use that when running server side to handle authentication in your function.

I don't want to go into it unless it's useful, but happy to provide a fuller explanation / example of it if it's relevant to what you want to do.

iaincollins avatar Jul 21 '18 07:07 iaincollins

Would love to see an authentication example, if possible.

I tried using your code above and received a "express.all is not a function" error. in the first one and a "nextApp.getRequestHandler() is not a function" in the second

webbygregg avatar Aug 03 '18 08:08 webbygregg

Supporting Isomorphic Calls That Need Authentication If you need to be able to make authenticated calls from both the client and the server, you can pass the req object from getInitialProps({req}) your function and you can use that when running server side to handle authentication in your function.

I don't want to go into it unless it's useful, but happy to provide a fuller explanation / example of it if it's relevant to what you want to do. https://github.com/iaincollins/next-auth/issues/8#issuecomment-406778233

Do you mind giving an example? This would be super helpful!

ericadamski avatar Jan 30 '19 12:01 ericadamski