I want to create a next.js 14 app and use its api routes to connect a RN mobile app. But the thing is I am new to next.js and don’t have much experience or understanding of cookies but I have worked with express.js and JWT tokens.
All the helping material and tutorials I could find uses sessions or cookies and packages like nextauth to handle auth that works for the client side of the next.js web app but what about the mobile app. how can I use that nextauth package to autherize apis in RN mobile app. Can I use jwt tokens for mobile routes and session for web frontend or is there a better way to handle this scenario?
Example of a secured Next.js API route (pages/api/secure-endpoint.js):
import jwt from 'jsonwebtoken';
// Secret key for signing/verifying the JWT (ensure this is stored securely, e.g., in environment variables)
const SECRET_KEY = process.env.JWT_SECRET;
export default async function handler(req, res) {
const token = req.headers.authorization?.split(' ')[1]; // Extract token from Authorization header
if (!token) {
return res.status(401).json({ message: 'Unauthorized, token missing' });
}
try {
// Verify the token
const decoded = jwt.verify(token, SECRET_KEY);
// Proceed with your logic if token is valid
return res.status(200).json({ message: 'Success', user: decoded });
} catch (error) {
return res.status(401).json({ message: 'Invalid or expired token' });
}
}
then you can use it on android something like below:
fetch('https://your-nextjs-app.com/api/secure-endpoint', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`, // JWT sent from mobile app
'Content-Type': 'application/json',
}
});
1. Authentication and Token Storage
JWT (JSON Web Tokens): Use JWT tokens for user authentication. Typically, you'll issue a token upon successful login, which will be stored on the mobile app. JWT is then sent in headers for API requests to verify and authorize users.
Secure Storage: Store the token in a secure location on the mobile device:
iOS/Android Native Storage: Use secure storage methods like the Keychain (iOS) or Keystore (Android) for sensitive data.
LocalStorage/SessionStorage: Avoid these for sensitive data due to XSS vulnerabilities. Use them only for non-sensitive session-related data.
2. Server-Side Authorization Logic
Next.js 14 offers enhanced support for server-side rendering (SSR) and static site generation (SSG). Combine this with server-side authorization:
Middleware Authentication: You can use Next.js middleware to intercept requests and check authorization before serving a page.
API Routes Protection: Protect API routes by checking for an authentication token (like a JWT) in the headers.
SSR with Authentication: When using getServerSideProps or getInitialProps, check for the authentication status server-side, allowing only authenticated users to access certain pages or content.
export async function getServerSideProps(context) {
const token = context.req.headers.cookie?.token;
if (!token) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
// Validate token and fetch user data here
return {
props: { user },
};
}
nishchaySharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.