Our latest article explains the key points about Using Cookies with Nextjs in Local Development. When developing Next.js applications locally, it’s important to understand how to properly configure cookies so they function as expected. Cookies allow you to store data on the client-side and are commonly used for authentication, user preferences, and session management. However, browsers treat cookies differently for localhost compared to deployed domains.
Here are a few additional steps you can take to further diagnose and resolve the problem:
- Check the Network Requests: Using your browser’s developer tools, examine the network requests made during the login process. Look for the request to the
/api/auth/callback/github
endpoint and check the response. The response might contain more detailed error information. - Review the GitHub App Configuration: Double-check the configuration of your GitHub OAuth app. Make sure that the “Authorization callback URL” is set to
http://localhost:3000/api/auth/callback/github
and that the app has the necessary permissions/scopes. - Examine the NextAuth.js Callbacks: If you have custom callbacks defined in your NextAuth.js configuration, ensure that they are correctly implemented. Sometimes, issues in the
signIn
orredirect
callbacks can lead to errors during the OAuth process. - Test with a Different Provider: To isolate the issue, try configuring a different OAuth provider (e.g., Google or Twitter) in your NextAuth.js setup. If the error persists with other providers, it might indicate a problem with your NextAuth.js configuration or the way your application handles sessions.
- Check for Redirect Issues: Ensure that there are no unintended redirects happening in your application that might interfere with the OAuth callback process. For example, if you have middleware or server-side logic that redirects users based on certain conditions, it could disrupt the OAuth flow.
- Consult the NextAuth.js Documentation: Review the NextAuth.js documentation for OAuth callbacks and ensure that your implementation aligns with the recommended practices.
If you continue to experience issues, consider providing more details about your NextAuth.js configuration and the specific steps you’re taking when encountering the error. This information can help in pinpointing the exact cause of the problem.
The localhost Exception
Typically, cookie domains require at least two dots to be valid by browsers. For example, “www.example.com” is a valid cookie domain, while “example” is not. This rule helps prevent cookies from one domain from being accessed by another.
However, localhost is a special case. It is treated as a top-level domain, even though it doesn’t contain any dots. As a result, setting cookies on localhost requires a different approach compared to other domains.
Configuring Cookies for Localhost
When setting cookies for a Next.js app running on localhost, you should omit the domain attribute entirely. Do not set the domain to an empty string, null, or false. Most frameworks and libraries will still send an empty Domain= attribute in those cases, which can cause issues.
For example, when using the Next.js API to set cookies:
res.setHeader('Set-Cookie', cookieName=cookieValue; Path=/; HttpOnly; Secure; SameSite=Strict);
Note that the Domain attribute is not included at all. The other attributes like Path, HttpOnly, Secure, and SameSite can still be used as needed.
If you are using another way to set cookies, like the cookie npm package, make sure to check its documentation on how to properly omit the domain when needed.
Localhost Subdomains
Some developers use localhost subdomains like site.localhost for local development. In those cases, you can set the cookie domain to “.localhost” and it will be accessible on all localhost subdomains. However, this is not widely supported across browsers.
The 127.0.0.1 Alternative
Since 127.0.0.1 contains dots, some developers use that instead of localhost to avoid cookie issues. You can run your local Next.js server on 127.0.0.1 and set cookies using that “domain”. Most browsers will accept cookies set on 127.0.0.1.
However, this approach can cause confusion, especially if your codebase or browser checks explicitly look for “localhost”. It’s cleaner to use localhost and omit the cookie domain as recommended.
Browser Inconsistencies
While the practices described here reflect the standards and how most browsers behave, there can still be some inconsistencies.
Safari and Firefox may handle localhost cookies slightly differently than Chrome. If you encounter issues, try testing in a different browser. Using Chrome’s incognito mode with extensions disabled is a good troubleshooting step.
Some browsers treat session cookies (those without an expiration or max-age attribute) on localhost differently than persistent cookies. Chrome may retain localhost session cookies across browser restarts, while other browsers delete them as expected.
Secure and HttpOnly Flags
When setting cookies, consider using the Secure and HttpOnly flags for improved security. The Secure flag ensures the cookie is only sent over HTTPS connections, while HttpOnly prevents client-side JavaScript from accessing the cookie.
In Next.js API routes, you can set these flags like this:
res.setHeader('Set-Cookie', cookieName=cookieValue; Path=/; HttpOnly; Secure; SameSite=Strict);
Note that the Secure flag will only work if your local development server is running with HTTPS enabled. You can use a tool like mkcert to generate self-signed certificates for localhost.
Cookie Parsing Libraries
If you need to parse cookies in your Next.js app, there are several popular libraries available. The cookie npm package is widely used and provides a simple API for reading and setting cookies.
To use it in your Next.js app, first install the package:
npm install cookie
Then, you can import and use it in your API routes or getServerSideProps:
import { serialize } from 'cookie';
export default function handler(req, res) { res.setHeader('Set-Cookie', serialize('cookieName', 'cookieValue', { path: '/' })); res.status(200).json({ message: 'Cookie set' }); }
The cookie package handles the intricacies of cookie formatting and encoding for you.
Cookie Size Limits
Be mindful of the size of your cookies, as browsers impose limits on the total size of cookies per domain. The exact limit varies between browsers, but it’s generally around 4KB.
If you need to store larger amounts of data, consider using other storage mechanisms like localStorage, sessionStorage, or a server-side session store.
Debugging Cookie Issues
When debugging cookie-related issues in your Next.js app, browser developer tools are your friend. In Chrome or Firefox, you can use the Application or Storage tab to inspect the cookies set for your localhost domain.
Look for any unexpected cookie values, attributes, or domain settings. Make sure your cookies are being set and sent correctly in your network requests and responses.
If you’re still encountering issues, try clearing your browser cookies and cache, or testing in a different browser or incognito mode.
Summary
When developing Next.js apps locally, remember to omit the domain attribute entirely when setting cookies on localhost. This will ensure the best compatibility and behavior across browsers. Be mindful of how your specific Next.js setup, cookie library, and browser handle localhost cookies. Understanding these nuances is essential for effectively managing client-side storage for your Next.js applications.