0
0
NextJSframework~10 mins

JWT vs session strategy in NextJS - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a JWT token using the jsonwebtoken library.

NextJS
const jwt = require('jsonwebtoken');

const token = jwt.[1]({ userId: 123 }, 'secretKey');
Drag options to blanks, or click blank then click option'
Adecode
Bverify
Csign
Dencrypt
Attempts:
3 left
💡 Hint
Common Mistakes
Using verify instead of sign to create a token.
Trying to decode or encrypt instead of signing.
2fill in blank
medium

Complete the code to set a session cookie in Next.js API route.

NextJS
import { withIronSessionApiRoute } from 'iron-session/next';

export default withIronSessionApiRoute(async function handler(req, res) {
  req.session.user = { id: 1 };
  await req.session.[1]();
  res.send('Logged in');
}, {
  password: 'complex_password',
  cookieName: 'myapp_session',
  cookieOptions: { secure: process.env.NODE_ENV === 'production' }
});
Drag options to blanks, or click blank then click option'
Asave
Bset
Ccommit
Dstore
Attempts:
3 left
💡 Hint
Common Mistakes
Using commit or set which are not methods in iron-session.
Forgetting to await the save method.
3fill in blank
hard

Fix the error in the code that verifies a JWT token.

NextJS
import jwt from 'jsonwebtoken';

try {
  const decoded = jwt.[1](token, 'secretKey');
  console.log(decoded);
} catch (err) {
  console.error('Invalid token');
}
Drag options to blanks, or click blank then click option'
Adecode
Bverify
Csign
Dencrypt
Attempts:
3 left
💡 Hint
Common Mistakes
Using sign instead of verify to check a token.
Using decode which does not verify the token's signature.
4fill in blank
hard

Fill both blanks to create a Next.js API route that clears a session cookie.

NextJS
import { withIronSessionApiRoute } from 'iron-session/next';

export default withIronSessionApiRoute(async function handler(req, res) {
  req.session.[1] = null;
  await req.session.[2]();
  res.send('Logged out');
}, {
  password: 'complex_password',
  cookieName: 'myapp_session',
  cookieOptions: { secure: process.env.NODE_ENV === 'production' }
});
Drag options to blanks, or click blank then click option'
Auser
Bsave
Csession
Dcommit
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the wrong session property to null.
Using commit instead of save to persist changes.
5fill in blank
hard

Fill all three blanks to create a JWT token with expiration and verify it.

NextJS
import jwt from 'jsonwebtoken';

const token = jwt.[1]({ id: 42 }, 'secretKey', { expiresIn: [2] });

const decoded = jwt.[3](token, 'secretKey');
Drag options to blanks, or click blank then click option'
Asign
B'1h'
Cverify
Ddecode
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of verify to check the token.
Not setting expiration correctly.